jQuery, Ajax, Json and Php
Facts - HTML and Javascript
Thursday, 09 October 2008 19:16

There are several ways for passing data between a webserver and a browser with Ajax. You could pass data using XML data structures or using JSON java structures.

XML is a way for representing data with a complex structure. At the time of this writing browser support for XML is still poor: there is no standard way for parsing/rendering XML data within javascript that is supported by the most used browsers. Therefore many websites use JSON to pass data between the browsers and the server. Fortunately JSON is well supported within javascript and server side scripting languages such as PHP. It has more or less the same capabilities for representing data with a complex structure.

Here I will first expand on repeating datastructures in XML and JSON. Then I will show how to pass complex JSON objects between browser javascript (jQuery) and PHP.

Suppose we have a repeating xml-structure as below.


The question is how this structure translates to JSON/javascript:

var data = 
      "sales": [ 
         { "firstname" : "John", "lastname" : "Brown" },
         { "firstname" : "Marc", "lastname" : "Johnson" }
      ] // end of sales array

As shown this is a name-value type syntax with colons in between. The rectangular brackets define the array, the curly brackets define the start and the end of a JSON objects. Note that in javascript the item tag is missing. The sales object can be accessed as follows:

alert("first item: " +employees.sales[0])
var extraSales = { "firstname" : "Mary",
                    "lastname"  : "Doe"};
data.sales[employees.sales.length] = extraSales; // add extra sales record (with index 2)
alert("extra sales from: " +data.sales[2].firstname); // shows "Mary"

The JSON records are accessed using an index starting from zero. This is similar to accessing the item tags in the xml using XPath. In that case the index starts from one. Furthermore a JSON substructure must be created first before its subfields can be accessed or set. For example:

  data.sales[3]= extraSales; // or: data.sales.push(extraSales);
// the next statement is ok because sales[3] is has been created before
  data.sales[3].firstname = "Pete";

It is easy to pass JSON objects between jQuery and PHP. Below is an example html file simpleform.html doing an ajax call to a PHP script simpleformSubmit.php. This webpage sends a JSON object, which is echoed by the PHP script.

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<title>Simple form sending and receiving a JSON object to/from PHP</title>
<script type="text/javascript" src="../../jQuery/jquery-1.2.6/dist/jquery.pack.js"></script>
<script type="text/javascript" src="../../jQuery/plugins/json2.js"></script>
<script type="text/javascript"><!--
  var data = 
    "sales": [ 
      { "firstname" : "John", "lastname" : "Brown" },
      { "firstname" : "Marc", "lastname" : "Johnson" }
    ] // end of sales array
  var dataString = JSON.stringify(data);
  $.post('simpleformSubmit.php', { data: dataString}, showResult, "text");
function showResult(res)
  $("#fullresponse").html("Full response: " +res);
  var obj = JSON.parse(res);
  $("#sales1Lastname").html("Lastname of sales[1]: " +obj.sales[1].lastname);
  <div id="fullresponse"><span/></div>
  <div id="sales1Lastname"><span/></div>

The PHP script simpleformSubmit.php:

<?php // -*-php-*- (sets emacs to use php mode)
$logFile = 'logFile';
$res = json_decode(stripslashes($_POST['data']), true);
error_log("result: ".$_POST['data'].", res=".json_encode($res), 3, $logFile);
error_log(", sales1_lastname: ".$res['sales'][1]['lastname'], 3, $logFile);
error_log("\n", 3, $logFile);
header("Content-type: text/plain");
echo json_encode($res);

As shown this example uses the standard json script json2.js with methods JSON.stringify and JSON.parse to convert between the javascript object and a string from or for the server. My impression is that JSON.parse is pretty sophisticated: it prevents insertion of javascript code to some extend. Note also that in the PHP script I use stripslashes before decoding the JSON string. This is only necessary if magic_quotes_runtime or magic_quotes_gpc is on.