While working with AJAX, you will need to get data after sending request to the server. You can use three ways to get the data form the server.
- In xml Format
- HTML Format
- Json Format
Though xml has several advantages, however processing data at the client will put extra burden.
HTML, can easily be handle, is however more resource or you can say bandwidth extensive.
So JSON fall in the middle of both.
PHP provide a very easy way to create JSON response. Once you get data at client side you will need much later code to process response than xml document.
Let’s first look at the server side.
For example we have the following array.
$data = array(‘items’=>array(‘firstname’=>’faheem’, ‘lastname’=>’abbas’,’address’=>’pakistan’));
To create JSON response, simply write
This will give the following result
Now at the client side to send AJAX request, you will need to create the following code.
Keep in mind that we are using prototype for making AJAX request.
“http://localhost/getdata.php”, /* this is url of the php file that create JSON response.*/
var response = eval(‘(‘ + rsp.responseText + ‘)’);
var firstname = response.items(0).firstname;
var lastname = response.items(0).lastname;
var address = response.items(0).address;