Working with POSTed json objects in Django - javascript

I am trying to figure out how to deal with POSTed json objects in Django. I'm POSTing a json object to the server and want to use it like a python dictionary.
here is my js:
$.post(
"/projects/vote/",
obj,
function(data) {
//alert("Data Loaded: " + data);
alert(data["msg"]);
});
What I am returning (end of django view):
return HttpResponse(json.dumps(foo), mimetype="application/json")
where
foo = {"msg": str(postdata)}
In other words, I'm POSTing a json object to the server, and alerting the string of the python object I get on the server so I can see what's going on.
If my obj is:
var obj = {
'bulk': false,
'data': {
'chosen': '14',
'proj1': '15',
'proj2': '14',
'proj3': '16',
'more': false,
},
'data2': [
{
'a': 'apple'
},
{
'b': 'banana'
},
],
}
I get this in return:
<QueryDict: {u'data[proj3]': [u'16'], u'data[proj2]': [u'14'], u'data[chosen]': [u'14'], u'data[proj1]': [u'15'], u'bulk': [u'false'], u'data2[0][a]': [u'apple'], u'data[more]': [u'false'], u'data2[1][b]': [u'banana']}>
How come the structure of the json obj and python dict don't align? And how do I get the structure to be the same? e.g. instead of data2[0][a], I would get data2 as the key to another dictionary
How I'm getting postdata:
# django version 1.4
postdata = request.POST.copy()

You may post json as plain string using JSON.stringify like this:
$.post(
"/projects/vote/",
{msg: JSON.stringify(obj)},
function(data) {
//alert("Data Loaded: " + data);
alert(data);
});
Thus on server side you should just extract 'msg' from request.POST:
def view(request):
return HttpResponse(request.POST['msg'], mimetype="application/json")
Note, that JSON.stringify is not supported by default in some browsers and you may want to use json lib: https://github.com/douglascrockford/JSON-js

You don't show how you're getting postdata from the POST, but you should be using request.body (request.raw_post_data in versions before 1.4).

You did not post JSON data. Set the dataType parameter to json:
$.post(
"/projects/vote/",
obj,
function(data) {
//alert("Data Loaded: " + data);
alert(data["msg"]);
},
'json'
);

The server can simply return a string, and the js can be written like this:
$.post(
"/projects/vote/",
obj,
function(data) {
data=eval('(' + data+ ')');//get the json object from string.
//alert("Data Loaded: " + data);
alert(data["msg"]);
});
Hope this helpful.

Related

JSON POST request object showing unevaluated keys

I am trying to send an AJAX post request to Django. I have a valid JSON object, which i can print/view/stringify in browser, but when it arrives in Django, the keys are unevaluated (see Django view in 2nd code block).
JS:
/* prettify payload for back */
var makeUpdatePayload = function(fieldType, fieldArray) {
var orderInfo = fieldArray.map(function(field, idx) {
var fieldInfo = field.split('-field-')
return {
'pk': fieldInfo[1],
'order': idx
}
});
return {[fieldType]: orderInfo}
};
/* post payload */
var updateFieldOrder = function( payload ) {
console.log('in ajax')
console.log(JSON.stringify(payload)) // {"search":[{"pk":"9","order":0},{"pk":"7","order":1},{"pk":"6","order":2},{"pk":"8","order":3},{"pk":"5","order":4},{"pk":"4","order":5}]}
$.ajax({
type: "POST",
url: "update_field_order/",
dataType: "json",
data: JSON.parse( JSON.stringify(payload)),
});
};
var payload = makeUpdatePayload('search', ["search-field-9", "search-field-7", "search-field-6", "search-field-8", "search-field-5", "search-field-4"])
updateFieldOrder(payload);
in my django view:
def update_field_order(request, recipe_pk):
print('post')
print(request.POST) # <QueryDict: {'search[0][pk]': ['9'], 'search[0][order]': ['0'], 'search[1][pk]': ['7'], 'search[1][order]': ['1'], 'search[2][pk]': ['6'], 'search[2][order]': ['2'], 'search[3][pk]': ['8'], 'search[3][order]': ['3'], 'search[4][pk]': ['5'], 'search[4][order]': ['4'], 'search[5][pk]': ['4'], 'search[5][order]': ['5']}>
I've tried JSON.stringify then JSON.parse -ing the payload before sending, but this doesn't help, I still see the same formatting. With JSON.stringify(payload), I get the expected output:
`<QueryDict: {'{"search":[{"pk":"9","order":0},{"pk":"7","order":1},{"pk":"6","order":2},{"pk":"8","order":3},{"pk":"5","order":4},{"pk":"4","order":5}]}': ['']}>`
Why is this happening?
I can see that the data is not correctly evaluated on sending:
I'm not entirely sure what you mean by the keys are unevaluated, but to send the object in the POST request, you should stringify it in your ajax call:
data: JSON.stringify(payload),
and then in your view, retrieve the JSON from the request.body and load it using the json module:
import json
...
payload = json.loads(request.body.decode("utf-8"))

Yii2 and Ajax: How to send JSON object of arrays?

I am using Yii2 framework I need to send an array containing id of person and an array of id of groups from client to server.
I got the data from a Select2 component using jQuery. Then the server will response so the client can show it in a form. I mean it is not a Create or Update button of Yii2.
The client side send this json object:
var jsonData = {
persons: 111,
groups: [222, 333]
};
$.ajax({
url: "/persons/persons?idsGroups=",
data: jsonData,
dataType: 'json',
success: function(res) {
console.log(JSON.stringify(res, null, 4));
}
});
From ther server I need to get the groups but it doens't work:
public function getMyGroups($groups) {
return $groups;
}
My browser shows:
error{"readyState":4,"responseText":"Bad Request (#400): Invalid data received for parameter \"groups\".","status":400,"statusText":"Bad Request"}
But if I change the getMyGroups function to get the persons variable, it works:
public function getMyGroups($persons) {
return $persons;
My browser shows:
111
So what this error means? I think I am sending data in a wrong way but I don't know how to fix it.
I resolved in this way using this help: https://api.jquery.com/jquery.post/
var jsonData = {
'persons': 111,
'groups[]': [222, 333]
};
$.post("/persons/persons", jsonData)
.done(function(data) {
console.log("Data loaded: " + data);
});

node.js parse array from jquery ajax

I'm creating an application in node which will get the array sent from jquery Ajax, here is my code:
Ember.$.ajax
({
type:"PUT",
url:"http://localhost:3000/ids/",
data:
{
ids:[29,12,43],
},
dataType: 'json',
});
Here is my node.js code:
router.put('/ids/', function(req, res)
{
var data = req.body;
console.log(data);
console.log(data.ids);
});
The result is:
{ 'ids[]': [ '29', '12', '43' ] }
undefined
I've also tried to iterate over it, but the code:
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(key + " -> " + data[key]);
}
}
Is not working also. What can I do in that case?
The 'ids[]:' does not look like the correct format for a key in JSON - are you sure this is what the console is printing?
In any case, if the data you are receiving is coming in as a string (even when the string looks like JSON) - you could try and parse it into JSON object. Here is an example for your case:
router.put('/ids/', function(req, res)
{
var data = req.body;
//if the string is a properly formatted JSON, this should pass:
var dataJSON = JSON.parse(data);
console.log(data);
//then see if this gives you what you expect
console.log(dataJSON);
console.log(dataJSON.ids);
});
Give it a try and let me know if this helps.
UPDATE:
Seeing that the data you receive is not a well-formatted JSON, try changing the PUT request into something like this:
Ember.$.ajax
({
type:"PUT",
url:"http://localhost:3000/ids/",
data: JSON.stringify({'ids':[29,12,43]}),
dataType: 'json',
});
Give it a try and let us know what the console is printing on the server and if the problem persists.

Issue with JSON.stringify adding a extra \ and "" to my Json object

Hi I am creating using Javascript an array of object with a key and a value using the following code.
ValuesArray.push({ key: $(this).attr('someattribute'), value: $(this).val() });
As a result I have am array of object like this:
key:29; value: 'Country'
Key:12; value: '4,3,5'
when I am trying to stringify it and send that JSON in a post I am having a wrong formatted JSON with \ and " in places that I dont want so when I try to desirales that JSON as a JObject on codebehind with C# I am having trouble. How can I create a clean JSON using the stringify
var jObject = JSON.stringify(ValuesArray);
My JSON now which is wrong is:
{
"JObject": "[{\"key\":\"29\",\"value\":\"Country\"}, {\"key\":\"30\",\"value\":\"4,3,5\"}]"
}
I would like to have a JSON object like this
{
"JObject": [{"key":"29","value":"Country"},{"key":"30","value":"4,3,5"}]
}
without the quotes around the [] and the character \
Any good idea to solve it.
Thank you
More detail this how I am sending the JSON to my API
this is how I am sending the JSON to my Web API:
function PostAPIRequest(address) {
var jObject = JSON.stringify(ValuesArray);
var responseJson = null;
$.ajax({
url: address,
type: 'POST',
dataType: 'json',
data: { JObject: jObject },
success: function (data) {
responseJson = data
ProcessDataResponse(responseJson);
//TODO: REFRESH THE DATA GRID
},
error: function (xhr, ajaxOptions, thrownError) {
//TODO redirect to the error page and send error email there.
alert(xhr.status);
alert(thrownError);
}
})
}
and this how I am receiving it in my API controller
...
// POST api/datavalues/5
public string Post(int id, JObject value)
{
var temp = value;
...
It looks like you are placing a string as the value in your map. You should do something like:
var objMap = {"JObject" : ValuesArray};
var json = JSON.stringify(objMap)
What's happening is you are double json encoding your values array - note that your "invalid" JSON value is actually a JSON string rather than the array that you want.
EDIT
It looks like you are sticking in JSON strings of maps into an Array and then stringifying that. Here's a jsfiddle that should help you get what you are looking for - http://jsfiddle.net/4G5nF/
In your post request, try this
var jObject = {"JObject" : ValuesArray};
$.ajax({ url: address,
type: 'POST',
dataType: 'json',
data: jObject,
success: function (data) { .. }});
Note the change in the data attribute. That is a value that is automatically JSONified for you.
const config = {a: 1, b: 2}
console.log(JSON.stringify(JSON.stringify(config)))
"{\"a\": 1, \"b\": 2}"
May be you have an old prototype library.
As I remove it, bug has disappeared

accessing json data from jquery

I'm creating an ajax app using jQuery 1.4.2 and I've tried using using get(), post() and the ajax() method itself. My php service returns:
[{"k":"label0","v":0.5},{"k":"label1","v":99.43},{"k":"label2","v":2.46},{"k":"label3","v":46.29},{"status":"OK"}]
in my success callback I have tried accessing as json.status and json[0][0]
but it always returns "undefined". what am I doing wrong?
function getSysinfo(source) {
var json = null;
$.ajax({
url: source,
type: 'POST',
dataType: 'json',
success: function (data) {
json = eval("(" + data + ")");
$('#data').html(json.status);
alert(json[0][0]);
refreshChart(json);
},
error: function (request, status, error) {
alert("REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
return json;
}
I've been googling this for days. How the heck do I access the returned data? any help would be appreciated.
To access that status value you would need:
data[4].status
This is because it is an object stored in the the fifth element in an array, with status being a property on the object.
Your JSON-data looks like this:
[
{
"k": "label0",
"v": 0.5
},
{
"k": "label1",
"v": 99.43
},
{
"k": "label2",
"v": 2.46
},
{
"k": "label3",
"v": 46.29
},
{
"status": "OK"
}
]
You would have to read your status using
json[4].status
with the 4 as a magical number or length-1 - not desirable. I would consider modifying your servers response to something more useful like this:
{
"status": "OK",
"entries": [ ... ] // add your data here
}
In your success callback try:
var parsed = $.parseJSON(data);
$.each(parsed, function (i, jsondata) {
alert( jsondata.k );
alert( jsondata.v );
});
You don't need the eval("("+data+")");. jQuery is automatically parsing the JSON response for you because you specified dataType:'json'
From the jQuery docs for dataType:
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
no need to use eval any more use below code which can be more for json
$.getJSON(url+query,function(json){
$.each(json,function(i,value){
});
});
nategood already wrote that you don't need do do anything with data, it's already an object.
In this case it's an array, if you like to access the status, you need to retrieve it from the last item of the data-array(that's where you'll find it in this array):
data[data.length-1].status
But maybe you should think about another structure of your JSON, it doesn't look very comfortable.
Something like that:
{
"items":[
{"k":"label0","v":0.5},
{"k":"label1","v":99.43},
{"k":"label2","v":2.46},
{"k":"label3","v":46.29}
],
"status":"OK"
}
...should be easier to handle, because you can simply access data.status instead of first looking where you may find it inside the response(what may be error-prone ).
The data parameter is the decoded JSON as you can see in this example:
http://www.jsfiddle.net/rLprV/1/
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: formData,
showLoader:true,
success: function (response) {
var parsed = JSON.parse(JSON.stringify(response));
$.each(parsed, function (key, val) {
alert( val.name );
});
},
error: function (err) {
alert("Please enter a valid id")
}
});

Categories