PHP: Creating JSON response, a real world example

4 May

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>

3 Responses to “PHP: Creating JSON response, a real world example”

  1. gabriel solomon May 4, 2009 at 4:08 pm #

    nice example,
    it would be nice to see a followup with a zend framework controller as a back-end since.

  2. Faheem Abbas May 5, 2009 at 5:28 am #

    you can use Zend_Dojo_Data and its method toJson() for creating JSON response in your controller.
    It pretty easy if you are using Zend Framework.
    I’ve already write about it.

  3. Muhammad Ahmed March 3, 2011 at 9:10 am #

    Thanks for simple, yet useful example.

    Regards,
    Ahmed

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: