Sunday, July 12, 2009

Creating Json response in php, a nice example

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.
1. In xml Format
2. HTML Format
3. 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
echo json_encode($data); 

This will give the following result
{"items":{"firstname":"faheem","lastname":"abbas","address":"pakistan"}}

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.
<script>
function getData()
{
new Ajax.Request(

“http://localhost/getdata.php", /* this is url of the php file that create JSON response.*/
{
method:'post',
onSuccess: processData
}
);
}
function processData(rsp)
{
var response = eval('(' + rsp.responseText + ')');
var firstname = response.items(0).firstname;
var lastname = response.items(0).lastname;
var address = response.items(0).address;
}
</script>


That's it.

7 comments:

  1. Why do you access the first item with round brackets?

    var firstname = response.items(0).firstname;

    I thought of items as an array, so you access an item by [0] rather than (0).

    Is this a special feature of prototype?

    greetings David Schreiber

    ReplyDelete
  2. and where does the zend framework come in?

    ReplyDelete
  3. I have tried your sample and all other online samples but was unable to get response from ZEN_JSON_SERVER

    Here is my post on complete sample

    http://wcfabc.blogspot.com//2012/06/json-implementation-Issues-in-zend.html

    ReplyDelete
  4. hi
    getdata.php this where we got

    ReplyDelete
  5. bcoz i need to store in folder so please explain how to store in zend framework folder.

    Thanks

    ReplyDelete
  6. Very Nice article. It is really interesting to read. Keep more posting.
    villas for sale in Islamabad

    ReplyDelete