Tutorials

JSON Requests and Responses

Oct 27, 2008 insic 2 Comments

In the previous post about JSON, you know what JSON is and you see what JSON looks like and how it differs to XML.

Now, you are about to learn how to handle JSON Requests and Responses. Before we get started you need to have Zend Framework installed and running in you local webserver in order for you to run the sample code.

Requests to the server using Ajax and JSON are the same as with XML.

As with the XML string, your data is the JSON string and the method again must be a ‘POST’. That part is simple enough, but what about the server side of things? If JSON is just a notation for JavaScript, how will other languages interpret it? Luckily, JSON has been ported to pretty much every scripting language there is. For a full list, you should refer to the JSON site. Because our examples are in PHP, we have many choices for porting JSON. I will be using JSON-PHP in these examples.

The data we are sending to the server will look like this:

Now here is the PHP sample code that handles a JSON request from the client. Comments are inserted in the code for your guide.

In this example, the JSON string that is passed to the server is read into the variable $raw_data. The string is then decoded using the decode( ) method from the json class.

The decoded object looks like this:

From here, it is just a matter of looking through the array and pulling out the values of each index.

After that, an array is created with the response data. This array is encoded into a JSON string with the encode( ) method, and then it is sent back to the client.

The response to the client looks like this:

And then the client now responsible to parse the string.

We are done for now. The next part is Parsing JSON data. Hope this will help.

About the author: insic

Subscribe in my RSS Feed for more updates on Web Design and Development related articles. Follow me on twitter or drop a message to my inbox.

  • bruce

    if you are running php5, no libraries are needed

    echo json_encode($obj);
    or
    echo json_encode(array());

    etc…

    and the reverse

    $var = json_decode($_POST['data']);

  • http://www.lautre-monde.fr/webtech/json/ Olivier

    Don’t forget also to check the magic quotes and then accurately stipslashes from the json object sent by the client to the server…