Все Едно Все Едно - 6 months ago 26
Ajax Question

AJAX POST , having problems with "data" field

I am using auto generated the ajax with Postman 3, so you can tell if it's the correct way to do it, but this isn't my main question. Now, when I type the "data" field like this, it works

var settings = {
"async": true,
"crossDomain": true,
"url": "https://baas.kinvey.com/appdata/kid_B1BHxEN7/people/",
"method": "POST",
"headers": {
"authorization": "Basic Z2VzaGE6MTIzNA==",
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "8de908df-f970-524c-eb8b-d2f7f621a3ac"
},
"processData": false,
"data": "{\"name\":\"Peter\",\"id\":11}"
}

$.ajax(settings).done(function (response) {
console.log(response);
});


Now my question is, how do I put custom parameters in the "data" field.
I want something like this

var arr = [{"name": "Peter", "id": 12}, {"name": "Demeter", "id": 15}];

var settings = {
"async": true,
"crossDomain": true,
"url": "https://baas.kinvey.com/appdata/kid_B1BHxEN7/people/",
"method": "POST",
"headers": {
"authorization": "Basic Z2VzaGE6MTIzNA==",
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "e37d3063-406d-02c3-803f-0f32666b9d70"
},
"processData": false,
data: {"name": arr[0].name, "id": arr[0].id}
}

$.ajax(settings).done(function (response) {
console.log(response);
});


When i send this POST request it gives me back 400(Bad request)

Lux Lux
Answer

jQuery does not format your request as JSON but only as data url. You have to do this yourself:

data: JSON.stringify({"name": arr[0].name, "id": arr[0].id})
Comments