How to parse a nested json ajax object in Django views? - ajax

I need to make a request as follows:
var url="http://127.0.0.1:8080/simulate/";
$.ajax({
url: url,
type: 'POST',
data:{ student_num:10,
company_num:10,
students:"",
csrfmiddlewaretoken:'{{csrf_token}}',
companies:[{weight:10},{weight:11},{weight:9}]
},
success: function(data, textStatus, xhr) {
var text=xhr.responseText
console.log(text)
}
});
But in this way, the request.POST object is not organizing the companies into a nested json array. Instead it makes it into a 2D array as follows:
<QueryDict: {u'student_num': [u'10'], u'students': [u''], u'companies[2][weight]': [u'9'], u'companies[1][weight]': [u'11'], u'company_num': [u'10'], u'companies[0][weight]': [u'10'], u'csrfmiddlewaretoken': [u'RpLfyEnZaU2o4ExxCVSJkTJ2ws6WoPrs']}>
In this way, I feel hard to reorganize the companies into a list of objects. I checked some other questions, some people say we should do this:
companies:"[{weight:10},{weight:11},{weight:9}]"
And then use json.loads to parse the string back to a list of objects. But I am keep getting parsing error if I use codes like this:
company_array = request.POST['company_array']
company_array = json.loads(company_array)
or this:
company_array = json.load(StringIO(company_array))
So what should be the correct way to handle nested JSON object?

You should use JSON.stringify() to stringify your data before sending it:
$.ajax({
url: url,
type: 'POST',
data: { data: JSON.stringify({ student_num:10,
company_num:10,
students:"",
csrfmiddlewaretoken:'{{csrf_token}}',
companies:[{weight:10},{weight:11},{weight:9}]
}) },
success: function(data, textStatus, xhr) {
var text=xhr.responseText
console.log(text)
}
});
Then you can parse with json.loads() on the server side:
data = json.loads(request.POST.get('data'))

You might find the answers here useful: Reading multidimensional arrays from a POST request in Django

You can try look to django-SplitJSONWidget-form and get decision from it.

Related

ajax request in jquery, data sent to the server not working

var p = JSON.stringify(parameter);
console.log(p);
$.ajax({
type: 'POST',
url: 'http://abc.com/ajax.php',
data: p,
success: function(status) {
console.log(status);
}
});
console.log(p) shows {"o_fname":"hh","o_lname":"jkhk","o_email":"uifh#bjvh.com","o_phone":"","b_name":"bmnbmbm,b","b_address":"","b_city":"","b_postal":"","b_phone":""}
but in my http://abc.com/ajax.php page print_r($_POST) is giving me an empty array Array()
var p = JSON.stringify(parameter);
That is your problem.
When you pass string data to .ajax, it sends it “as-is” – but PHP only popuplates $_POST if it receives data encoded as application/x-www-form-urlencoded.
So don’t make your data into a string, but pass your parameter object directly as value for data – then jQuery will take care of sending it the right way, so that PHP understands what it is supposed to do with it.
I think park of the problem may be that in data: you're passing the parameter details, but to the function on the other side of the jQuery you're passing a parameter name and nothing else.
Try:
$.ajax({
type: 'POST',
url: 'http://abc.com/ajax.php',
data: {parametername:p},
success: function(status) {
console.log(status);
}
});
With parametername replaced with the parameter name ajax.php is expecting.

$.ajax() vs $.getJSON() with YQL and cross domain requests

I'm trying to execute a cross domain request for data from a wordpress blog using YQL. This is the code from my first attempt:
var g = {data:""}
function getWP() {
var targeturl = "http://www.mysite.com";
var url = "http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(targeturl)+
"%22&format=xml'&callback=?";
var successfunc = function(data) {
if(data.results[0]){
g.data = data.results[o];
} else {
var errormsg = '<p>Error: could not load the page.</p>';
alert(errormsg);
}
}
$.ajax({
url: url,
success: successfunc
});
}
When I tried this ajax call, the data object returned was an empty string. However, when I did this:
$.getJSON(url, successfunc);
the proper JSON object was returned. What is the difference between the two calls? And more importantly, why did only the second one work?
The difference is that you are not specifying your data type or content type
Add
$.ajax({
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: successfunc
});
to your ajax call
$.getJSON() uses data type json while the $.ajax() doesn't. If you want to use standard $.ajax() you'll have to specify datatype explicitly. For cross-domail calls use datatype jsonp instead of json. But I think YQL works with json as well.

MooTools: How do package data for a POST ajax request?

I'm using MooTools 1.4.1. I want to create an ajax post requst, but I can't figure out how to construct the "data" attribute, which I wish to contain the name value pairs of a form whose id is "myForm".
$('save').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'save',
data: { ... },
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
});
});
Anyone know how I should populate the "data" attribute? Thanks, - Dave
You can use
$('myForm').toQueryString();
Alternatively, The MooTools More package has a Form.Request() class to send a Form using Ajax.
As Savageman commented, you can throw your form element into toQueryString() and send it through in the data property, or by running .send() or .post() on the request object.
You also seem to be missing a closing squiggly bracket.
Anyhow, this is how I make AJAX requests:
new Request({
url: 'http://url/to/ajax/script.php',
onSuccess: function(data) {
doStuff();
}
}).post('action=foo&bar=baz');
I'd recommend you use Request.JSON if you're planning on sending stuff back. It's less "shotgun approach"-ey.
You can just pass form element to "data" property, and conversion is automatic.
var req = new Request({
method: 'post',
url: 'example.com/form.php',
data: $('myForm'),
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
}
});
data - (mixed: defaults to '') The default data for Request:send, used when no data is given. Can be an Element, Object or String.
If an Object is passed the Object:toQueryString method will be used to convert the object to a string.
If an Element is passed the Element:toQueryString method will be used to convert the Element to a string.
http://mootools.net/docs/core/Request/Request

how do I get the reponse text from ajax / jquery?

Imagine I run this:
$.ajax({
type: 'POST',
url: '/ajax/watch.php',
data: {'watch':'aukcia', 'id':aukciaID},
complete: function(responseText){
alert(responseText);
}
});
Inside /ajax/watch.php, let's say I have this:
echo 'this is what I want';
And the alert(responseText) returns:
[object Object]
Instead of my text string that I need.
Any help, please?
Looks like somehow your jQuery is returning the XMLHttpRequest object, instead of your response.
If that is the case, you should ask for its responseText property, like this:
$.ajax({
type: 'POST',
url: '/ajax/watch.php',
data: {'watch':'aukcia', 'id':aukciaID},
complete: function(r){
alert(r.responseText);
}
});
However, if that does not work, you might be actually receiving a JSON response, and the [object Object] you are seeing might be your browser's representation of your JSON response.
You should be able to inspect its contents by navigating around the object properties. However, if you want, you can also tell jQuery not to parse your JSON response, by including dataType: 'text' on your call:
$.ajax({
type: 'POST',
url: '/ajax/watch.php',
data: {'watch':'aukcia', 'id':aukciaID},
dataType: 'text',
complete: function(data){
alert(data);
}
});
For more information, see: http://api.jquery.com/jQuery.ajax/
Use on your client side ajax like this
$.ajax({
type: "POST",
url: "insert-data.php",
data:
{student_name:student_name,student_roll_no:student_roll_no
,student_class:student_class},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
in server side after query excecute you may use it give success when you query success false when your query has fault
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Probelm occur.";
echo json_encode($error);
}
I think you are receiving this in your server respones
{message:'hello world'}
if thats the case then use
JSON.parse(data.responseText).message
to convert the json string into javascript object and access your message property.

How to send multiple jQuery arrays to an MVC controller?

I have created and filled various arrays using jquery. First time, trying to send JavaScript arrays to MVC controller.
Can I have an example how to do that? How can I send the arrays and other variables as well? On the controller side, how can I retrieve the data?
You'll probably want to use jQuery.ajax, with a dataType parameter of 'json'. You can send any JSON object. Possible example:
var obj = {'foo': 'bar'};
$.ajax({
type: "POST",
url: "some.aspx",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: obj,
success: function(resp){
alert("Response: " + resp);
}
});
You can comma or pipe delimit your input and on the other end just parse it to keep things simple. Or if you want to do things the right object oriented way you could use the following code:
var object1 = $(".ControlArrayClass").val();
var object2 = $(".ControlArrayClass2").val();
$.post('mycontroller/myactionmethod', function( variable1: object1, variable2: object2});
and on the controller end it would look like this
public ActionResult myactionmethod(Guid[] variable1, String[] variable2)
{
//do whatever here
return View();
}
Hope this helps.

Resources