XML adds a lot of extra markup for most ajax requests. If you expect some kind of list with data entities, sending them in JSON format is the way to go.
I used JSON to get huge arrays of data.
First of all, JSON is just a Javascript object designation, meaning that an Ajax request requests a string that will actually be evaluated as a Javascript object.
Some browsers offer support for parsing JSON out of the box. Others need a little help. I used this little library to parse responseText in all the webapps I developed and had no problems with it.
Now that you know what JSON is and how to use it, here is what the PHP code looks like.
$response = [ "success" => true, // I like to send a boolean value to indicate if the request // was valid and ok or if there was any problem. "records" => [ $dataEntity1, $dataEntit2 //.... ] ]; echo json_enconde($response );
Try it and see what it is. I used php 5.4 array declaration syntax because it is cool! :)
When requesting data through Ajax, you will do:
var response ,xhr = getAjaxObject(); // XMLHttp or ActiveX or whatever. xhr.open("POST","your url goes here"); xhr.onreadystatechange=function() { if (xhr.readyState==4 && xhr.status==200) { try { response = JSON.parse(xhr.responseText); } catch (err) { response = { success : false, //other error data }; } if(response.success) { //your data should be in response // response.records should have the dataEntities console.debug(response.records); } } }
Summary:
- JSON parsing needs a little help through the JSON2 library.
- PHP can send maps as JSON
- Boolean success is widely used as the success / unsuccessful flag
Alternatively, if you are in jQuery, you can simply set the dataType: "json" property in the $ .ajax call to get the JSON response in the callback.
source share