JSON with Ajax

On this page we demonstrate how to pass variables from JavaScript to PHP using JSON and Ajax. We don't resort to a library like jQuery for this. Instead we take a hands-on approach and use the built-in JavaScript XMLHttpRequest and JSON.stringify objects and methods directly.

You can collect form data, as the GET and POST examples do, and prepare it for passage to the server using JSON. But JSON.stringify can also handle more complex data structures, such as the following:

var BookData = [ // outer level array literal
    { // second level object literals
        title: 'Professional JavaScript',
        author: 'Nicholas C. Zakas'
    },
    {
        title: 'JavaScript: The Definitive Guide',
        author: 'David Flanagan'
    },
    {
        title: 'High Performance JavaScript',
        author: 'Nicholas C. Zakas'
    }
];

You could have a link set up as follows to send this JavaScript array/object to PHP using the handleJSONData function displayed below:

<a href="#" onclick="handleJSONData(BookData); return false;">Click Me</a>

The handleJSONData function is set up to handle the JavaScript array or object you pass to it. The function formats the data as JSON, initiates the XMLHttpRequest by calling the dw_makeXHRRequest function, and handles the response from the server:

function handleJSONData( data ) {
    
    // callback object defines functions that handle success and failure of request
    var callback = {
        success: function(req) {
            document.getElementById('result').innerHTML = req.responseText;
        },
        failure: function(req) {
            document.getElementById('result').innerHTML = 'An error has occurred.';
        }
    }
    
    // arguments: url, callback object, request method, data (stringified), data type
    dw_makeXHRRequest( 'json.php', callback, 'POST', JSON.stringify(data), 'application/json' );
}

The callback object contains success and failure methods which you can define to suit your purposes. The dw_makeXHRRequest function is expecting these and invokes the appropriate function depending upon the success or failure of the request. Notice that the request object (req) is passed to these functions, providing access to responseText and other properties of the object.

Finally, the dw_makeXHRRequest function is called with the following arguments: URL, callback object, method (POST), stringified data, and data type ('application/json').

Find out more about JSON.stringify and how you can use a replacer or the toJSON method to exercise more control over the data sent in your Ajax request.

PHP Access to Values Sent using JSON and Ajax

The following demonstrates how PHP can access the JSON string sent in the Ajax request:

// how to access data sent using JSON
$jsondata = file_get_contents('php://input');

// http://php.net/manual/en/function.json-decode.php
$books = json_decode( $jsondata, true ); // 2nd arg true to convert objects to associative arrays

// more info at http://www.dyn-web.com/tutorials/php-js/json/decode.php
echo $books[1]['title'];

The php://input stream provides access to the JSON data sent in the request body.[1] PHP's file_get_contents function is used to retrieve it. The result is assigned to a $jsondata variable. Then we use the json_decode function to convert $jsondata to an array, passing true as the second argument to convert the second-level objects to associative arrays. Finally, we demonstrate how to access elements in the resulting multidimensional array.[2]

A working example is provided in the download file.


  1. $HTTP_RAW_POST_DATA could also be used but is deprecated as of PHP 5.6. See more in the PHP Manual. ^
  2. Find out more about json_decode. ^