Yii ajax return html page - html

there! I have a problem with receive data from my ajax query. It's return html code of the page.
My ajax code
$.ajax({
url: 'index.php?r=site/page&view=mail',
type: 'post',
data: {action: 'smtp_save', smtp_login: login, smtp_password: password, smtp_server: server, smtp_port: port },
success: function($output) {
//debug message
alert($output);
}
})
Php, just for test only
if(isset($_POST['action']) && !empty($_POST['action']))
{
echo 'test';
}

What do you expect? of course it return HTML. If you do not set the return data type specifically, it tries to guess the dattatype.
And as you output only "test" so it is HTML of course.
If you want JSON you should do 2 things:
set the type to JSON with dataType:'json'
user this php code: echo json_encode('test')
And if you do this all in the controler/action, then you should add Yii::app()->end();
after the echo, otherwise Yii renders the whole page output. This way you only get what you have echod out

Related

Pass AJAX param and access it from expressjs side of application

I feel like I am missing something here.
To start, you have an AJAX call you can do in tag to post data to the backend, which looks something like,
function changeDom(){
console.log('connecting');
$.ajax({
url: '/loadOrders',
method:'POST'
}).done(function(data){
if(data.success){
$('#recentOrders').append(data.message);
changeDom2();
return;
}
}).fail(function(){
console.log('failed');
return;
});
};
And on the backend you receive it with code that looks something like,
app.post('/loadOrders', function(req,response)
{ // code here });
I have seen that it is possible to pass a parameter along an AJAX call, which looks like,
$.ajax({
url: '/loadOrders',
method:'POST',
data: {field1: 'this is data being passed'}
}).done(function(data){}});
But how would I receive that data on the backend? How would that change in syntax look and how would I call the parameter?
You can get it by doing
req.body.field1

Search mysql database with node in html

I connected a database to node and am trying to create an HTML page to search the database. I would rather not use EJS. I think I have to use a POST request in the HTML AJAX and connect it with a POST request in node.
Here is what I'm thinking:
app.post("/cities/:city", function(req, res) {
db.hospitalinfo.findAll({
where: { city: req.params.city }
}).then(function (result) {
res.json(result);
console.log("res--->"+result);
console.log("req--->"+req.params.city);
});
});
Here's the HTML:
<form id="author-form" method="POST">
<select id ="dropDownId">
<option value="Opp" >Opp</option>
<option value="Boaz">Boaz</option>
</select>
<input class="SubmitButton" type="submit" id="click" style="font-size:20px;" />
</form>
Now here's where I'm stuck. I need to grab the value from the select statement:
var nameInput = $("#dropDownId :selected");
I don't know how to actually send nameInput to the URL so my post statement will work. I probably don't completely understand how these routes work. This is my first project by myself. I would like to grab the nameInput, send it to the server via AJAX, and search my database with it. Right now it's returning an empty object. Thank you for your help.
You need to make a Ajax call to node server. For that you need to stop the default submit of form.
event.preventDefault();
can be used to stop the normal flow of submitting the form.
Here is an example of ajax call
(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type: "GET", // define the type of HTTP verb we want to use (POST for our form)
url: "http://localhost:5000/example" // the url where we want to POST
data: formData,
dataType: 'json', // what type of data do we expect back from the server
success: function (data) {
console.log(data.result);
// perform required changes
},
error: function (err) {
console.log(err);
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
you can refer this site for more details making ajax calls
I have modified the code taken from there.

How to JSON parse using form.errors.as_json() in Django return JsonResponse(data)

In Django, I tried using form.errors.as_json() to get all form errors and here is sample json data strings.
{"password2":[{"message": "This password is too short. It must
contain at least 8 characters.","code":"password_too_short"}]}
I wanted to loop and get all under "message" key in json so I can use it to notify the user after ajax call.
Thanks
Anyways, I just resolved my issue and just wanted to share what I did.
views.py
if form.is_valid():
...
else:
# Extract form.errors
errMsg= None
errMsg = [(k, v[0]) for k, v in form.errors.items()]
return JsonResponse(errMsg)
Ajax Event
$.ajax({
method: "POST",
url: '\your_url_here',
data: $form.serialize(),
cache: false,
dataType: "json",
beforeSend: function(){
//Start displaying button's working animation
//Do some button or loading animation here...
}
},
success: function(jResults)
{
//This line is to remove field name display
var strErr = jResults + ''; //make json object as string
strErr = strErr.split(",").pop();
alert(strErr);
}
});
Hope this help to anyone out there facing similar issue. By the way, I'm using Django 2.0 and Python 3.6+
Thanks
MinedBP
The correct answer should be:
return HttpReponse(form.errors.as_json(), status=400).
In the AJAX call you can get the content doing:
`$.post("{% url 'your_url'%}", your_payload).done(function(data) {
do_something();
}).fail(function(xhr){
// Here you can get the form's errors and iterate over them.
xhr.responseText();
});`
You are sending a 200 HTTP response, that it is wrong, you should return a 400 HTTP response (Bad request), like Django do without AJAX forms.

MVC - returning data via ajax call renders it as page

New to MVC.
Scenario is. Using a 3rd party upload library for images. When a form is submitted, I want to make a call via ajax to submit the data and return the inserted item id. I then use that id for the 3rd party upload library to build folders where the images will be uploaded to.
I have the ajax call working and inserting the data to the database and getting the inserted id. But when the debug returns from the controller, it renders the id as a whole page.
Missing something fundamental here to MVC I think.
cshtml file:
<div class="col-md-8">
<input type="submit" value="Add Item" id="submitItem" />
<script>
$(document).ready(function () {
$("#submitItem").submit(function () {
event.preventDefault();
insertData();
});
});
function insertData()
{
var requestData = {
userID: $("#hdnUserID").val(),
title: $("#title").val(),
typeID: $("#typeID").val(),
description: $("#description").val()
};
$.ajax({
url: '<%= Url.Action("ItemUserDashBoard", "Home") %>',
type: 'post',
data: JSON.stringify(requestData),
dataType: 'json',
success: function (data) {
// your data could be a View or Json or what ever you returned in your action method
// parse your data here
alert(data);
$("#fine-uploader-gallery").fineUploader("uploadStoredFiles");
},
processData: false
});
}
</script>
</div>
HomeController.cs
[HttpPost]
public JsonResult ItemUserDashBoard(ItemAppraise.Models.iaDashBoardModel objItemUserDashBoard)
{
if(ModelState.IsValid)
{
using (dbContext)
{
ia_items iaItem = new ia_items
{
userID = objItemUserDashBoard.iaItems.userID,
typeID = objItemUserDashBoard.iaItems.typeID,
title = objItemUserDashBoard.iaItems.title,
description = objItemUserDashBoard.iaItems.description,
lastUpdate = DateTime.Now
};
dbContext.ia_items.Add(iaItem);
dbContext.SaveChanges();
//objItemUserDashBoard.iaItems.itemID = iaItem.itemID;
return Json(iaItem.itemID.ToString());
}
}
else{
return null;
}
}
Fiddler shows it as having a header of Content-Type: application/json; charset=utf-8.
But the page renders under the control url 'http://localhost:55689/Home/ItemUserDashBoard' with just the item id showing.
How do I get the data back just to use in the success part of the ajax call and not be rendered? Is this Partial Views or something similar?
Any guidance is appreciated.
In standard MVC. Any call made to a controller is handled just like a web request. So if i understand you correctly - the result of your httpPost is being rendered instead of the desired View? This is because you are returning JSON, so the controller assumes that is what you are trying to render. If you want a View to be rendered instead (and somehow use that response data) you could try setting the return type to ActionResult and returning a View("nameofview"); You can pass your response data to that view in a number of ways.
As a side note I think the problem you are facing could be better solved with Web Api instead of MVC. It works well with MVC and could be a simpler way of implementing your desired functionality. Separating your post requests and database interactions from the logic which decides which View to return.

AJAX response using Jquery (with zend framework) contains unwanted HTML Code

Currently, the following code works as intended but if I add an echo such as "LANG: en" anywhere in the code (let's say in the bootstrap), the following code won't work anymore and I get this ajax request response :
<br/>LANG : en{"response":true,"id":13}
(the ajax response contains the echo + json array ) and therefore I'm not able to print the id (it will print : undefined when i will try to access to data.id).
My question is : How can I print my debug info and still manage to perform ajax requests ?
Here is my code in the controller :
public function init()
{
$this->_helper->ajaxContext->addActionContext('retrievecategories', 'json')->initContext();
}
public function retrievecategoriesAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if ($this->getRequest()->isXmlHttpRequest()) {
if (isset($_POST['id']))
$id = $_POST['id'];
$id+=1;
echo json_encode(array('response' => true, 'id' => $id));
}
}
My js code :
jQuery(function(){
var obj = {"id":12};
jQuery.ajax({
url: '/search/retrievecategories?json',
type: 'post',
data: obj,
dataType: 'json',
success: function(data){
var id = data.id;
alert(id);
},
error: function(data){
var id = data.id;
alert(id);
}
});
});
I hope I was clear enough. Thank you for your time !
If you echo anything but the JSON object, the JQuery parser will fail because the response is no longer a valid JSON. you could make a custom parser which interprets the response text and takes away the debug info leaving the JSON object, or you can include the debug info in the array you encode.
json_encode(array('data'=>'data','debug'=>'debug info'))
Then you detect if the debug field is present and after a console.log() or alert() you delete it form the object.
I would strongly recommend that you read about firePHP. It uses the same console that Firebug uses to display debug information from your php code. It is really simple to use with the Zend_Log.