JSON POST request object showing unevaluated keys - javascript

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"))

Related

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);
});

How to send json data from Angularjs post to Django view?

I need to send json data using a POST request from Angularjs to my Django view.
I need to get data from database using this json as json format.
I tried some examples using from net resources:
JS Code:
$http({
method: 'POST',
url: '/mycard/list',
data: $.param({test: json})
});
Python Code(Django View):
def product_list(request):
if len(request.META['QUERY_STRING']) > 0:
data = request.body
data = json.loads(data)
print data
else:
f = open('./mytest.txt','r')
data = f.read()
return HttpResponse(data, mimetype='application/json')
But it returns 403 error and sometimes it returns 500 error(INTERNAL SERVER ERROR)
Service Code
var promise = $http({
method: 'post',
url: '/mycard/list',
data:data,
contentType:'application/json; charset=UTF-8',
});
return promise;
Python rest api
#csrf_exempt
#api_view(['GET','POST'])
def product_list(request):
if request.method == 'POST':
try:
stream = StringIO(request.body)
data = JSONParser().parse(stream)
except ValueError:
return Response(json.dumps(ValueError, default=json_util.default))
return Response(json.dumps(data, default=json_util.default))
else:
return Response("failure")
your json data should be formatted by JSON.stringify() like this:
$http({
method: 'POST',
url: '/mycard/list',
data: JSON.stringify({test: json})
});
403 Forbidden maybe because of an invalid CSRF token
500 : You might be not posting the data in the format that the backend is expecting. Can you please inspect and see what is the error response it is giving.

My Json get cut off when sent with Ajax

I'm using angular to save new data on the database, I take the data from my inputs, put it in a object and I convert it to a Json, I send it by POST, but my JSON gets cut off and I have no clue why is it happening.
var myJson = angular.toJson(myObject);
$http({
method: 'POST',
url: 'http://url/file.php',
data: {
'data': myJson
}
})
.success(function (data){
console.log(data);
})
My file.php has a var_dump($_POST) in it, and it shows that:
[
{
"uuid":"56456456456456456456465456"
},
{
"store_name":"",
"store_email":"",
"store_facebook":"",
"contact_name":"John Doe",
"contact_email":"email#email.com",
"contact_facebook":"http://localho
Angular's http post method sends whatever data it is passed to. You should check your generated json data after
var myJson = angular.toJson(myObject); using console.log(myJson);
and that itself must be cut off.

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

Working with POSTed json objects in Django

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.

Categories