Working with JSON in PHP jQuery

Exclusive offer: get 50% off this eBook here
PHP jQuery Cookbook

PHP jQuery Cookbook — Save 50%

Over 60 simple but highly effective recipes to create interactive web applications using PHP with jQuery

$23.99    $12.00
by Vijay Joshi | December 2010 | Open Source PHP

In this article, by Vijay Joshi, author of PHP jQuery Cookbook, we will cover:

  • Creating JSON in PHP
  • Reading JSON in PHP
  • Catching JSON parsing errors
  • Accessing data from a JSON in jQuery

 

PHP jQuery Cookbook

PHP jQuery Cookbook

Over 60 simple but highly effective recipes to create interactive web applications using PHP with jQuery

  • Create rich and interactive web applications with PHP and jQuery
  • Debug and execute jQuery code on a live site
  • Design interactive forms and menus
  • Another title in the Packt Cookbook range, which will help you get to grips with PHP as well as jQuery
        Read more about this book      

(For more resources on this subject, see here.)

Introduction

Recently, JSON (JavaScript Object Notation) has become a very popular data interchange format with more and more developers opting for it over XML. Even many web services nowadays provide JSON as the default output format.

JSON is a text format that is programming-language independent and is a native data form of JavaScript. It is lighter and faster than XML because it needs less markup compared to XML.

Because JSON is the native data form of JavaScript, it can be used on the client side in an AJAX application more easily than XML.

A JSON object starts with { and ends with }. According to the JSON specification, the following types are allowed in JSON:

  • Object: An object is a collection of key-value pairs enclosed between { and } and separated by a comma. The key and the value themselves are separated using a colon (:). Think of objects as associative arrays or hash tables. Keys are simple strings and values can be an array, string, number, boolean, or null.
  • Array: Like other languages, an array is an ordered pair of data. For representing an array, values are comma separated and enclosed between [ and ].
  • String: A string must be enclosed in double quotes
  • The last type is a number

A JSON can be as simple as:

{
"name":"Superman", "address": "anywhere"
}

An example using an array is as follows:

{
"name": "Superman", "phoneNumbers": ["8010367150", "9898989898",
"1234567890" ]
}

A more complex example that demonstrates the use of objects, arrays, and values is as follows:

 

{
"people":
[
{
"name": "Vijay Joshi",
"age": 28,
"isAdult": true
},
{
"name": "Charles Simms",
"age": 13,
"isAdult": false
}
]
}

An important point to note:

{
'name': 'Superman', 'address': 'anywhere'
}

Above is a valid JavaScript object but not a valid JSON. JSON requires that the name and value must be enclosed in double quotes; single quotes are not allowed.

Another important thing is to remember the proper charset of data.

Remember that JSON expects the data to be UTF-8 whereas PHP adheres to ISO-8859-1 encoding by default.

Also note that JSON is not a JavaScript; it is basically a specification or a subset derived from JavaScript.

Now that we are familiar with JSON, let us proceed towards the recipes where we will learn how we can use JSON along with PHP and jQuery.

Create a new folder and name it as Chapter 4. We will put all the recipes of this article together in this folder. Also put the jquery.js file inside this folder.

To be able to use PHP's built-in JSON functions, you should have PHP version 5.2 or higher installed.

Creating JSON in PHP

This recipe will explain how JSON can be created from PHP arrays and objects

Getting ready

Create a new folder inside the Chapter4 directory and name it as Recipe1.

How to do it...

  1. Create a file and save it by the name index.php in the Recipe1 folder.
  2. Write the PHP code that creates a JSON string from an array.

    <?php
    $travelDetails = array(
    'origin' => 'Delhi',
    'destination' => 'London',
    'passengers' => array
    (
    array('name' => 'Mr. Perry Mason', 'type' => 'Adult',
    'age'=> 28),
    array('name' => 'Miss Irene Adler', 'type' => 'Adult',
    'age'=> 28)
    ),
    'travelDate' => '17-Dec-2010'
    );
    echo json_encode($travelDetails);
    ?>

  3. Run the file in your browser. It will show a JSON string as output on screen. After indenting the result will look like the following:

    {
    "origin":"Delhi",
    "destination":"London",
    "passengers":
    [
    {
    "name":"Mr. Perry Mason",
    "type":"Adult",
    "age":28
    },
    {
    "name":"Miss Irene Adler",
    "type":"Adult",
    "age":28
    }
    ],
    "travelDate":"17-Dec-2010"
    }

How it works...

PHP provides the function json_encode() to create JSON strings from objects and arrays. This function accepts two parameters. First is the value to be encoded and the second parameter includes options that control how certain special characters are encoded. This parameter is optional.

In the previous code we created a somewhat complex associative array that contains travel information of two passengers. Passing this array to json_encode() creates a JSON string.

There's more...

Predefined constants

Any of the following constants can be passed as a second parameter to json_encode().

  • JSON_HEX_TAG: Converts < and > to \u003C and \u003E
  • JSON_HEX_AMP: Converts &s to \u0026
  • JSON_HEX_APOS: Converts ' to \u0027
  • JSON_HEX_QUOT: Converts " to \u0022
  • JSON_FORCE_OBJECT: Forces the return value in JSON string to be an object instead of an array

These constants require PHP version 5.3 or higher.

PHP jQuery Cookbook Over 60 simple but highly effective recipes to create interactive web applications using PHP with jQuery
Published: December 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources on this subject, see here.)

Reading JSON in PHP

Opposite to the previous recipe, this recipe will explain how JSON strings can be read in PHP and converted to objects or arrays. Decoding JSON strings is very easy in PHP with its JSON functions.

Getting ready

Create a new folder named Recipe2 in the Chapter4 directory.

How to do it...

  1. Create a file named index.php in Recipe2 folder.
  2. Now try to convert a JSON string to object using json_decode() method . After that, print the resulting object on screen. For json_decode(), you can use the output from previous recipe which is a valid JSON string.

    <?php
    $json = <<<JSON
    {
    "origin":"Delhi",
    "destination":"London",
    "passengers":
    [
    {
    "name":"Mr. Perry Mason",
    "type":"Adult",
    "age":28
    },
    {
    "name":"Miss Irene Adler",
    "type":"Adult",
    "age":25
    }
    ],
    "travelDate":"17-Dec-2010"
    }
    JSON;
    echo '<pre>';
    $objJson = json_decode($json);
    print_r ($objJson);
    echo '</pre>';
    ?>

  3. Run the index.php file in the browser and you will see the structure of JSON string in the form of an object. To access the values from this object, you can query it just like any other object in PHP.

How it works...

json_decode() converts valid JSON strings into objects. It accepts three parameters each of which is described below:

  • The JSON string itself.
  • Optional parameter assoc: By default this value is false. If changed to true, json_decode will convert objects to associative arrays.
  • Depth: Maximum allowed depth of a recursive structure in the JSON string. It used to be 128 before PHP 5.3. PHP 5.3 has this limit increased to 512 bytes default. This parameter is also optional.

In the previous code we used the HEREDOC syntax to define a JSON string. Then we passed this string to the json_decode() function which converted it to an object.

We can now access the values from this object using standard PHP operators. For example, to get the travel date from this object use:

$objJson->travelDate

Similarly,

$objJson->passengers[1]->name

will output the name of a second passenger, that is, Miss Irene Adler

Catching JSON parsing errors

Errors are a part of application development. It depends on how the developer handles them to ease the life of users. While encoding or decoding JSON it may happen that the value passed to these JSON functions is erroneous or violates the JSON rules. In such cases you should always try to catch these errors and handle them.

This recipe deals specifically with error handling for JSON functions. We will use PHP's inbuilt JSON error handling methods to detect any errors in JSON.

 

>Please note that error handling in JSON is only available in PHP versions 5.3 and higher. So make sure you have the correct version of PHP installed to use this feature.

Getting ready

Create a new folder inside the Chapter4 directory and name it as Recipe3. Also make sure you have PHP version 5.3 or higher installed.

How to do it...

  1. Create a new PHP file index.php in the Recipe3 folder
  2. Using the same JSON string as present in the previous recipe, try to convert it into an object. Then write a switch case that will check for any errors in JSON and will output the result accordingly.

    <?php
    $json = <<<JSON
    {
    "origin":"Delhi",
    "destination":"London",
    "passengers":
    [
    {
    "name":"Mr. Perry Mason",
    "type":"Adult",
    "age":28
    },
    {
    "name":"Miss Irene Adler",
    "type":"Adult",
    "age":25
    }
    ],
    "travelDate":"17-Dec-2010"
    }
    JSON;
    $objJson = json_decode($json);
    switch(json_last_error())
    {
    case JSON_ERROR_NONE:
    echo'Travel date is:' . $objJson->travelDate;
    break;
    case JSON_ERROR_DEPTH:
    echo 'The JSON string has exceeded maximum allowed stack
    depth';
    break;
    case JSON_ERROR_CTRL_CHAR:
    echo 'Control character error';
    break;
    case JSON_ERROR_SYNTAX:
    echo 'Incorrect JSON : Please check your JSON syntax';
    break;
    }
    ?>

  3. Now, run the index.php file. Since JSON is correct, you will see the output Travel date is:17-Dec-2010 on your screen. Now remove the comma from the line "destination":"London",. Save the file and reload it. You will see an error message : Incorrect JSON : Please check your JSON syntax

How it works...

PHP version 5.3 onwards provides a function json_last_error(). This function takes no parameters and captures the last error through JSON parsing. It returns an integer value that can be checked to know the specific error. PHP has some predefined constants for these error values. These are:

  • JSON_ERROR_NONE: It means the JSON was parsed successfully and there was no error
  • JSON_ERROR_SYNTAX: Means there is a syntax error in the JSON string
  • JSON_ERROR_CTRL_CHAR: Invalid control character encountered
  • JSON_ERROR_DEPTH: The JSON string has exceeded maximum allowed stack depth

Accessing data from a JSON in jQuery

So, now we know how to generate JSON using PHP. We can put this knowledge of ours to some real use. We will write an example that will request some JSON data from PHP (using jQuery of course) and then we will display it in the web page.

Getting ready

Create a folder for this recipe inside the Chapter4 directory and name it as Recipe4.

PHP jQuery Cookbook Over 60 simple but highly effective recipes to create interactive web applications using PHP with jQuery
Published: December 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources on this subject, see here.)

How to do it...

  1. Create a file named index.html in the newly created Recipe4 folder.
  2. Write some HTML code in this file that will create and empty select box and an empty unordered list. Also define some CSS styles for these elements in the &lthead> section.

    <?php
    <html>
    <head>
    <title>Accessing data from a JSON</title>
    <style type="text/css">
    body,select,ul{ font-family:"trebuchet MS",verdana }
    ul{ list-style::none;margin:0pt;padding:0pt;}
    </style>
    </head>
    <body>
    <h3>Select a date to view Travel Details</h3>
    <p>
    <select id="travelDates">
    </select>
    <ul>
    <li id="origin"></li>
    <li id="destination"></li>
    <li id="travellers"></li>
    </ul>
    </p>
    </body>
    </html>
    ?>

  3. Time for some jQuery now. First, add a reference to the jQuery library, just before the closing of the tag. Then, write the jQuery code that will request some JSON data from a PHP file json.php. On receiving the response, jQuery will fill the select box and will bind a change event handler for it. On selecting a value from this select box, another function will be called that will search for the JSON response for the selected date and will display relevant details on finding it.

    <script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="../jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function ()
    {
    var jsonResult;
    $.getJSON("json.php",displayData);
    function displayData(data)
    {
    jsonResult = data;
    var str = '<option value="">select a date</option>';
    for(var i=0; i<data.length;i++)
    {
    str+= '<option value="' + data[i].travelDate + '">' +
    data[i].travelDate + '</option>';
    }
    $('#travelDates').html(str);
    $('#travelDates').change(function()
    {
    if($(this).val() != '')
    {
    displayDetails($(this).val());
    }
    });
    }

    function displayDetails(selectedDate)
    {
    for(var i=0; i<jsonResult.length;i++)
    {
    var aResult = jsonResult[i];
    if(aResult.travelDate == selectedDate)
    {
    $('#origin').html('<strong>Origin : </strong>'+
    aResult.origin);
    $('#destination').html('<strong>Destination :
    </strong>'+ aResult.destination);
    var travellers = aResult.passengers;
    var strTraveller = '<ul>';
    for(var j=0; j<travellers.length;j++)
    {
    strTraveller+= '<li>';
    strTraveller+= travellers[j].name;
    strTraveller+= '</li>';
    }
    strTraveller+= '</ul>';
    $('#travellers').html('<strong>Travellers : <br/>
    </strong>'+ strTraveller);
    break;
    }
    }
    }
    });
    </script>

  4. Now let's get to the file that will receive the request for JSON. Create this new file and save it as json.php. In this file, create an array of travel details of some travellers, then convert it to JSON and send it to the browser.

    $travelDetails = array(
    array(

    'origin' => 'London',
    'destination' => 'Paris',
    'passengers' => array
    (
    array('name' => 'Mr. Sherlock Holmes', 'age'=> 34),
    array('name' => 'Mr. John H. Watson', 'age'=> 32)
    ),
    'travelDate' => '17-Dec-2010'
    ),
    array(
    'origin' => 'Delhi',
    'destination' => 'London',
    'passengers' => array
    (
    array('name' => 'Mr. Albert Einstein', 'age'=> 51),
    array('name' => 'Mr. Isaac Newton' ,'age'=> 43)
    ),
    'travelDate' => '25-Jan-2011'
    ),
    array(
    'origin' => 'Delhi',
    'destination' => 'London',
    'passengers' => array
    (
    array('name' => 'Prof. John Moriaty', 'age'=> 44),
    array('name' => 'Miss Irene Adler', 'age'=> 28)
    ),
    'travelDate' => '30-Mar-2011'
    )
    );
    header('Content-Type:text/json');
    echo json_encode($travelDetails);

  5. All done now. Open your browser and run the index.html file. A select box will appear on screen with some dates filled in it. Select a date and you will see the details for that particular date.

How it works...

When the DOM is ready, we call the AJAX method $.getJSON(). Previously, you learnt about $.get() and $.post(). Similarly, this is a special method that is used when the expected data from the server is in JSON format. Here is the breakdown of parameters of $.getJSON():

  • URL: This is the URL where the request will be sent.
  • URL: This is the URL where the request will be sent.
  • Data: The data (if any) that has to be sent to the server.
  • Callback function: This function is fired when the response is received from the server. In case of a JSON response, jQuery parses it and a JavaScript object of the parsed data is made available to the callback function.

In our example, the request is sent to the json.php file first, where an array with multiple records has been declared. We then use the json_encode method to convert this array to JSON and echo it to the browser.

On receiving the response jQuery parses it and an object is made available to the callback method, displayData. Here we store it in a global variable $jsonResult for future use.

Then we iterate in this object and fill the select box with all the travel dates in the array. Because the data is now a JavaScript object, JavaScript syntax will apply to it.

After the select box is filled with data, we attach a change event handler for it. When a value is selected from the select box, the displayDetails() function is called. This function searches the object for the selected date. When the date is found we retrieve the values for origin, destination, and passengers from the selected set and insert them into corresponding elements on the page.

There's more...

Other AJAX methods for requesting JSON data

As mentioned earlier, $.getJSON() is solely designed for conditions where we know in advance that the response from the server is going to be JSON. However, this behavior can be simulated with other high-level AJAX methods like $.get(), $.post() and the low level implementation $.ajax().

$.get(
'json.php',
displayData,
'json'
);

By specifying the last parameter as JSON, jQuery will try to assume the response as JSON string and will try to parse it. Same can be done with $.post() and $.ajax().

Handling errors while requesting JSON

The method that we have used above use AJAX methods such as $.getJSON or $.get. These methods do not have error-handling abilities by themselves. For example, if we have requested JSON using $.getJSON and the server sends malformed JSON, $.getJSON will fail silently. There are two ways to resolve this: either use the ajaxError() method, which gets executed when any AJAX request encounters an error, or use the low level $.ajax method, which provides both success and error callbacks. Both of these have been described in detail in the recipe Handling errors in AJAX requests in the previous article.

Parsing a JSON

Other than using $.getJSON or specifying a data type in AJAX requests, you can also parse a valid JSON string to convert it to JSON object. jQuery provides a method parseJSON() to convert a JSON string to a JavaScript object.

var objJSON = jQuery.parseJSON('{"key":"value"}');

objJSON is now a JavaScript object.

Another method, which is not recommended, is to use eval() function of JavaScript.

 

var objJSON = eval('(' + '{"key":"value"}' + ')')

Using eval() may harm your site as the eval() will execute any data that is passed to it. Therefore, it is recommended to use either parseJSON or a specific AJAX method of jQuery that returns parsed JSON.

Summary

In this article we have covered:

  • Creating JSON in PHP
  • Reading JSON in PHP
  • Catching JSON parsing errors
  • Accessing data from a JSON in jQuery

Further resources on this subject:


About the Author :


Vijay Joshi

Vijay is a programmer with over six years of experience on various platforms. He discovered his passion for open source four years back when he started playing with PHP on a hobby project. Vijay now is a professional web developer and prefers writing code ONLY in open source (but that does not always happen, unfortunately!). He switches hats as needed – he is full-time lead programmer at Philogy, independent consultant for few selected companies where he advises them on variety of internet-based initiatives and still remains an active blogger at http://vijayjoshi.org.

Outside of work, he enjoys reading, trekking, and sometimes gets obsessed with fitness. Currently Vijay lives in New Delhi with his brother and a close network of friends that he is proud of.

Books From Packt


Drupal 7
Drupal 7

PHP 5 E-commerce Development
PHP 5 E-commerce Development

Expert PHP 5 Tools
Expert PHP 5 Tools

PHP 5 CMS Framework Development - 2nd Edition
PHP 5 CMS Framework Development - 2nd Edition

jQuery 1.4 Animation Techniques: Beginners Guide
jQuery 1.4 Animation Techniques: Beginners Guide

CMS Design Using PHP and jQuery
CMS Design Using PHP and jQuery

jQuery Plugin Development Beginner's Guide
jQuery Plugin Development Beginner's Guide

jQuery 1.4 Reference Guide
jQuery 1.4 Reference Guide


Your rating: None Average: 4.4 (7 votes)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
G
M
v
t
n
z
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software