I am trying to post an array of objects from jQuery/Javascript client script to server side PHP script.
Im still confused about the format that the object array data should be in before reaching the server.
I create an array to store the json objects
var jsonObjects = [];
I add individual json objects to the array
var jsonObj1 = {};
jsonObj1.place = "London";
jsonObj1.position = 1;
jsonObjects.push(jsonObj1);
var jsonObj2 = {};
jsonObj2.place = "Melbourne";
jsonObj2.position = 2;
jsonObjects.push(jsonObj2);
..etc
I then try to post this data via ajax post (Ive tried stringifying before the post and also tried without stringifying)
e.g.
//var data = jsonObjects;
//var data = JSON.stringify(jsonObjects);
jQuery.ajax({
url: "/drupal/menu_item",
type: 'POST',
data: data
dataType: 'json'
});
Either way on the XHR tab in Firebug it just shows a stringified version of the data
e.g.
[{“place”:”London”,”position”:”2″}, {“place”:”Melbourne”,”position”:”2″}]
rather than it looking like what the post details have looked like before with the data broken up into parameters. Unless of course PHP finding data in the stringified state will actually work (?)
I seem to be finding conflicting details as to how sending an array of json objects to PHP should be done. At the point that the ajax request is executed what state should the data be in?
a) stringified array of objects
b) array of objects
c) something else again (?)
Any help to clarify this is much appreciated 🙂
Thanks,
Rowan
Stringified data is just a textual representation of a JS object. Therefore, you can run
json_decodeon the stringified JS object in order to obtain PHP data structure.On the other hand, if your objects are simple key:value ones without much depth (multi-dimensional arrays) then they can be sent as querystring and parsed into PHP’s
$_POST/$_GET/$_REQUEST