Dictionary inside dictionary from AJAX to Django - json

My javascript code is like this:
var emotions = {};
$('#emotions').children('#emotionFields').each(function(){
emotions[$(this).find($('.emotion')).val()]=$(this).find($('.value')).val()
});
$.ajax({
url: '../data',
dataType: 'json',
type: 'GET',
data: {action: 'dosomething',word:word,emotions:emotions},
success:function(response){
//something
},
error:function(msg){
//somethin
}
});
So just before the ajax call my emotions object looks like this:
emotions: Object
excitement: "value1"
guilt: "value2"
When I read this data from djangos request.GET I see
{u'action': u'dosomething',
u'emotions[excitement]': u'value1',
u'emotions[guilt]': u'value2',
u'word': u'word'}
Now, How do I convert this to a proper dictionary where I can access the excitement and guilt ?

Before sending your data try doing a JSON.stringify().
...
$.ajax({
...
contentType : "application/json",
data : JSON.stringify({action: 'dosomething',word:word,emotions:emotions}),
...
...
And then in your Django view:
...
data = json.loads(request.body)
print data['emotions']['guilt']
...
If the above code does not satisfy your requirement then you can use this library.
EDIT: If Django version is <1.6 then use request.raw_post_data instead of request.body.

Related

Unexpected end of JSON input... SO Wants more info

I'm confused... What's wrong with this?
Couldn't post without changing the title... I seriously don't know what's wrong
$(document).ready(function(){
$("#fmob").click(function(){
var mobname = $(this).attr("data-value");
console.log(mobname);
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: {mobname: 1},
dataType: "json",
success: function(data){
if(data.response === true){
$("#fresponse").html(data.result);
}else{
$("#fresponse").html(data.result);
}
},
error:function(jqXHR,textStatus,errorThrown ){
alert('Exception:'+errorThrown );
}
});
});
});
I looked up here Unexpected end of JSON input from an ajax call
but somehow not what I expected... What's wrong? Thanks.
Try this approach:
$(document).ready(function(){
$("#fmob").click(function(){
var mobname = $(this).attr("data-value");
console.log(mobname);
var data = {}; // setup a data object
data[mobname] = 1; // add the property with the key of the value of the "mobname" variable, with the data of 1 (per question)
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: data, // pass the data object as the POST data instead of defining an object inline
dataType: "json",
success: function(data){
if(data.response === true){
$("#fresponse").html(data.result);
}else{
$("#fresponse").html(data.result);
}
},
error:function(jqXHR,textStatus,errorThrown ){
alert('Exception:'+errorThrown );
}
});
});
});
Note the lines with comments, above.
In this approach, we setup a data object and specify a property using the value of the "mobname" variable, instead of defining the property inline. This allows us to use the dynamic value of the variable as the key for the property.
I guess the problem is with the line: data: {mobname: 1}
As you can't assign a variable name as object property like that... it should be inside a square brackets like this data: {[mobname]: 1}
EDIT: if you aren't using browser supported by ES 2015 you could even do
data: JSON.parse('{"'+mobname+'":1}')
EDIT 1 if you want to send the json data as string and convert that on php side you could simply do data: '{"'+mobname+'":1}'
This might cause your ajax call to fail, and might not return a JSON as you're expecting (using the line dattype:JSON);
So removing datatype:JSON can also help you by showing what you're doing wrong
JSON objects are differentiated from standard JavaScript objects by using double quoted in both the key and the value - unless either is an integer.
It is explained in the relevant W3Schools site.
Therefore, in your AJAX request, you have to send a properly formatted JSON object:
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: {"mobname": 1}, //here's the change
dataType: "json",
/* rest of the code */
You can of course pass a variable as well:
var JSON_obj = {"mobname": 1, "othermob": 2, /*rest of the JSON */ };
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: JSON_obj, //here's the change
dataType: "json",
/* rest of the code */
Again, with properly formatted JSON objects (and with properly included JS script if it's in another file), this should work.

ajax json : how to retrieve data from json object received by ajax?

Here is the code:
$.ajax({
url: MyURL,
method: 'GET',
processData: true,
contentType: 'application/json;',
dataType: "json",
success: function(data) {
alert("Success data= "+JSON.stringify(data));
var count = Object.keys(data).length;
alert("count = "+count );
result=data[0];
alert("result.CountryName:"+ result.CountryName);
alert("total " + keys.length + " keys: " + keys);
error: function(data) { alert("ajax Error"); },
});
The 1st alert seems ok and gives:
Success data= "[{\"CountryName\": \"france\", \"Currency\": \"Euro\", \"PriceMax\": 500.00, \"PriceStep\": 50.00, \"PriceMin\": 100.00}]"
From the firebug/network/response i see the same data (with the backslash!!)
The 2nd alert gives 107. Apparently each character is an object ?
But when i check the syntax on http://jsonlint.com/ the json is correct.
Finally the last alert gives: undefined.
So what is wrong ?
Thank you for your help
The data you're sending is an array containing a single object. You'll need to use data[0]['CountryName'].
The response that you have is not an JSON object, it is a String. So you need to parse it to a JSON and then take the first position of the array.
json_data = JSON.parse(data)
result = json_data[0]
and then you use a property of that object:
result.CountryName
The problem was the slash in the json string.
I read Why does JSON returned from the django rest framework have forward slashes in the response? and make some modif in my django code.
i changed return JsonResponse(simplejson.dumps(data), safe=False)
to return JsonResponse(data, safe=False) and the slash disappeared then the javascript code worked.
Thanks for your help Daniel and Rubico

Post Raw Json via .submit()

How can I post username/password as Raw JSON via form.submit().
loginForm.submit({
url: 'localhost/login',
method: 'post',
jsonData: loginForm.getValues()
...
success: ...
even with Ext.JSON.encode(loginForm.getValues()) server is receiving as username=test&password=test which I need to be {"username":"test","password":"test"}
You should probably try something like
Ext.Ajax.request({
method: 'POST',
url: 'submit.php',
params : {
data: Ext.encode(loginForm.getValues())
},
success: function() {
},
failure: function() {
}
});
Source for reference
As is often the case with ExtJS, there's an easy answer. In the config of the loginForm:
Ext.create('Ext.form.Panel', {
title: 'Simple Form',
// The form will submit an AJAX request to this URL when submitted
url: 'save-form.php',
.... (blah blah blah)
jsonSubmit: true // <---- set this to TRUE
});
Set the property jsonSubmit: true. Then when you use loginForm.submit(), your object will be submitted as JSON rather than form params.
Here's a link to the form docs:
http://docs.sencha.com/extjs/4.2.3/#!/api/Ext.form.Panel
When a form is submitted, it is not submitted in JSON format.
In order to submit JSON string, Ext.Ajax.request must be used.
http://www.sencha.com/forum/showthread.php?132082-jsonData-in-submit-action-of-form
I just had to change
loginForm.submit({})
to
Ext.Ajax.request({})
and use
params: Ext.JSON.encode(loginForm.getValues()),
Bad DOCS.

Angular JS POST request not sending data

I am trying to send an JSON object to my webservice which is expecting JSON in the request data.
This my POST call from angularJS
$http({method: 'POST',
url: 'update.htm',
data: $.param($scope.cover),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data) {
// handle
});
Value for cover object
$scope.cover = {id:1, bean:{id:2}}
Iam getting 500 (InvalidPropertyException: Invalid property 'bean[id]' of bean class [BookBean]: Property referenced in indexed property path 'bean[id]' is neither an array nor a List nor a Map;)
In network, it is sending in this way
bean[id]:1
I think it should send like
bean.id:1
How to reslove this issue. Thanks in advance
Looks like the data is getting to the server and is causing an error there. There's a possible duplicate question that's been answered here - Post Nested Object to Spring MVC controller using JSON
Try posting your data like:
$http({method: 'POST',
url: 'update.htm',
data: $scope.cover,
}).success(function (data) {
// handle
});

Using jQuery and JSON with AJAX responseText?

Ok, I'm a bit new when it comes to jQuery and json. If I'm using json as my return type, can I still retrieve responseText from an XMLHttpRequest object?
here's the code that i'm using:
json response: {"clients": []}
$.ajax({
type: "POST",
url: "/myurl/whatever.php",
data: myData,
dataType: "json",
success: function(msg){
status.html(msg[0]);
},
error: function(msg) {
status.html("Error: " + msg[0]);
}
});
is the use of msg[0] correct if i want to output the json response or am i missing something?
how can i still use the above code with XMLHttpRequest to get the status, responseText, etc.
thanks, all!
As far as I know, the call to $.ajax returns a XHR object, and from that the responseText can be extracted, e.g.:
var xhr = $.ajax( {
url:' someInfo.php',
data: 'which=squirrels',
asynch: true
} );
var resp = xhr.responseText;
The response text will contain a json string, which would need to be converted to an object to be of any use.
If you want to use the response as a json object directly within your success: function, do as #cloudhead suggested, and use msg. The dataType : "json" in your options takes care of the conversion for you.
If you're using json, then you get a json object back, not an XML object. You can output it directly, without using [0].