Purchased the book on Amazon.com or received a free copy at a user group or conference? Click here to create your account!

« Back to the blog

Gluing jQuery and PHP Together with JSON

Published on: June 23, 2009 @ 08:29:50 · 0 comments

The ability to create powerful Web interfaces using AJAX is accomplished thanks to the marrying of a server-side language such as PHP and the client-side JavaScript language. But how is data passed between a script executing on the server and another executing within the user's browser, all without going through the usual request-response process which requires the page to reload? For many developers, the solution is the jQuery JavaScript library, and a convenient data format called JSON (pronounced JAY-SON). In this tutorial I'll introduce you to JSON, and show you how to pass data between a PHP script and JavaScript function to dynamically display a list of favorite books similar to that shown in Figure 1.

See the end of this blog post for a very special promotional offer for "Easy PHP Websites with the Zend Framework!

Favorite Books

Figure 1. Recent Amazon sales rank data

Introducing JSON

Programming languages aren't unlike their spoken siblings in that although each language sports a grammar and vocabulary for describing a particular concept, each approach is ultimately unique and only understood within each language's respective boundaries. For instance, while both PHP and JavaScript share a very similar definition of an array, each language possesses its own unique syntax and methods for creating, parsing, and managing this important data construct; accordingly, the JavaScript approach won't work within PHP, and vice-versa. So how can the two languages successfully pass an array back and forth in a mutually understood fashion?

They do this by agreeing upon a specific format for passing the data between the respective languages, with each language using its own built-in features for converting, or translating that data into a natively understood syntax. One of the most commonly used data-interchange formats is JSON (JavaScript Object Notation). Supported by dozens of languages, among them C#, Java, JavaScript, PHP, and Python, JSON is a rare beast in that it uses a format easily understandable by humans while also easily created and parsed by programming languages.

Formatting PHP Data in JSON Format with PHP

PHP includes a native JSON-parsing capabilities as of version 5.2. To encode an array into JSON format, just create the array, and then pass it to the json_encode() function, as demonstrated here:

$isbns = array("9780307346612", "0765318741", "9780441783588");
$isbnsJSON = json_encode($books);

It's also possible to encode multi-dimensional arrays, which is a much more common occurrence when building AJAX-enabled websites:

$books = array();

$books[] = array("isbn" => "9780307346612", "title" => "World War Z");
$books[] = array("isbn" => "0765318741", "title" => "I Am Legend");
$books[] = array("isbn" => "9780441783588", "title" => "Starship Troopers");

$booksJSON = json_encode($books);

Likewise, you can also decode JSON-formatted data, converting the data into a native PHP array using the json_decode() function. Once converted, you can use PHP's native array behavior to interact with the data in the typical fashion.

But how is this data sent from PHP to a JavaScript program, and how does a JavaScript program send it to PHP? The beauty of this marriage is that it's built on the bedrock of the tried-and-true HTTP communication protocol. Using the familiar GET and POST methods, the JSON-formatted data can be shuttled back-and-forth with ease. What's better, JavaScript libraries such as jQuery make this task trivial.

jQuery and JSON

jQuery includes built-in support for retrieving JSON-formatted data from a server-side script using the $.getJSON function. In the following example (book.html), clicking the button identified by the ID button will cause the $.getJSON function to execute, contacting a server-side PHP script named books.php. Any JSON-formatted data returned from books.php will be passed into the callback function as an array, and subsequently output to the browser.

<html>
    <head>
    <title>My Favorite Books</title>
    <script type="text/javascript" src="jquery-1.3.2.min.js"></script>  
    <script type="text/javascript">
        $(document).ready(function() {
            $("#button").click(function() 
            {
                $.getJSON('books.php',
                    function(data) {
                        var textToInsert = [];
                        var i = 0;
                        var length = data.length;
                        for (var x = 0; x < length; x += 1) {
                            textToInsert[i++] = data[x].title + " (" + data[x].isbn + ")<br />";
                        }
                        $('#favorite-books').append(textToInsert.join(''));
                    }
                )
                return false;
            });
        });
    </script>
    </head>
    <body>
        <input type="button" name="button" id="button" value="Show My Favorite Books" />
        <div id="books"></div>
    </body>
</html>

Pressing the "Show My Favorite Books" button produces the output shown in Figure 1.

Incidentally, it's possible to abuse jQuery's .append() method in seemingly countless ways. I've employed the approach found in the preceding example after reading Josh Powell's post, "43,439 reasons to use append() correctly".

As the getJSON() call indicates, the JavaScript contacts the books.php script. This script is presented next:

<?php

    // Create the array
    $books = array();
    $books[] = array("isbn" => "9780307346612", "title" => "World War Z");
    $books[] = array("isbn" => "0765318741",    "title" => "I Am Legend");
    $books[] = array("isbn" => "9780441783588", "title" => "Starship Troopers");

    // Encode the array in JSON format
    $booksJSON = json_encode($books);

    // Return the data to the caller
    echo $booksJSON;

?>

Sending JSON Data to a PHP Script

Retrieving JSON-formatted Data from a PHP Script is easy enough, but the Web is a two-way street. How can we send JSON-formatted data entered through an HTML form to a PHP script using jQuery? The solution is easier than you might think. To make the JSON conversion process easier, download the jQuery plugin jquery-json, available from the Google code website:

http://code.google.com/p/jquery-json/

Add it to your project directory, and reference it in the same fashion you did to reference the jQuery JavaScript file. Next, we'll create the form shown in Figure 2. Following the figure you'll find the code used to create this form; add it to the body of the books.html file. Note how each form element is accompanied by a unique ID.

Adding a book

Figure 1. Adding a book using Ajax and JSON

<div id="form-response"></div>

<form id="book-form">

<p>
Book Title:<br />
<input type="text" name="title" id="title" value="" size="35" />
</p>

<p>
Book ISBN:<br />
<input type="text" name="isbn" id="isbn" value="" size="15" />
</p>

<p>
<input type="submit" name="addbook" id="addbook" value="Add Book" />
</p>

</form>

Next, add the following function within the body of the anonymous function declared by $(document).ready. This is an event handler which will trigger when the form's submit button is pressed. Take a moment to review the code and accompanying comments.

$("form#book-form").submit(function() {

    var book = new Object();

    // Retrieve the title and ISBN
    book.title = $('#title').val();
    book.isbn = $('#isbn').val();

    // Use the jquery-json plugin to convert the form data to JSON
    var bookJSON = $.toJSON(book);

    // Contact addbook.php, passing in the JSON
    $.post('addbook.php',
        {book: bookJSON},
        function(data) {
            var ds = $.evalJSON(data);
            if (ds.result == 1) {
                $('#form-response').html("The book has been added to your collection.");
            } else {
                $('#form-response').html("Something seems to be wrong.");
            }
        }
    )
return false;
});

Finally, the addbook.php PHP script follows. This is a simple proof-of-concept script intended to show you how to decode the JSON and insert it into a MySQL database. Obviously in a real-world situation some data validation and error handling would be required.

<?php

    // Connect to the MySQL database
    $db = new mysqli("localhost", "webuser", "secret", "book");

    // Decode the JSON, converting it to an associative array
    $book = json_decode($_POST['book'], true);

    // Make the data easier to reference
    $isbn = $book['isbn'];
    $title = $book['title'];

    // Insert the data into the MySQL table
    $query = "INSERT INTO books VALUES(NULL,'$title','$isbn')";
    $result = $db->query($query);

    $db->close();

    // Presuming insertion was successful, encode message and return
    $res["result"] = 1;
    echo json_encode($res);

?>  

As an exercise, try revising the books.php script found earlier in this tutorial to retrieve the books from the MySQL database!

Like this Tutorial?

Jason's new book, "Easy PHP Websites with the Zend Framework", shows you how to build powerful websites using PHP, MySQL, and the Zend Framework. Included with each purchase is access to almost five hours of online video, a regularly updated PDF, and the opportunity to directly communicate with the author!

To celebrate the start of summer, we're offering the e-book + video access for just $18, and the print book + e-book + videos for just $25*! This offer is only mentioned within this week's blog posts, and ends at midnight on June 26th! To take advantage of this offer, use the code summer1 when purchasing the e-book, and summer2 when purchasing the print book!

* (print book available in U.S. only)

Comments

Nobody has commented on this blog post yet. Why don't you be the first?

Add a Comment

Only registered users can ask questions and post comments. If you're already registered login now. Don't have an account? Registering only takes a moment and it's free! Register now.

 Join 700+ subscribers!


Have a question? Contact us!

The Tag Cloud

The Community Firehose

News submitted by and about the PHP and Web development community.

Creating a Weather Forecast with PHP and the Google Weather API
Submitted by wjgilmore

How to Create an Image Gallery Powered By PHP and Picasa
Submitted by wjgilmore

Easy Databasing with SQLite
Submitted by wjgilmore

PHP IDE Roundup
Submitted by wjgilmore

Five Cool PHP Array Functions
Submitted by wjgilmore

Use jQuery with Greasemonkey
Submitted by wjgilmore

Encapsulation in PHP
Submitted by wjgilmore

Talking to Google Charts with PHP
Submitted by wjgilmore

Talking to Google Analytics with PHP
Submitted by wjgilmore

Building a jQuery/PHP-powered Chat Room
Submitted by wjgilmore

Cloud Computing with PHP
Submitted by wjgilmore

BattleMaster: A Web-based game written in PHP
Submitted by wjgilmore

Create an Image Rotator with CSS and jQuery
Submitted by wjgilmore

Submit News | News Archive

Copyright © 2009 W.J. Gilmore, LLC. All Rights Reserved. Purchase Policy · Privacy Policy
Trademarked names may appear on this website. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to no benefit of the trademark owner, with no intention of infringement of the trademark.