Before JSON, the most common way to create powerful web2.0 applications is to combine AJAX with XML. However, the major setback of using the AJAX and XML duo is the extra lengthy code that needs to be embedded in the client’s webpage in order to decode the XML returned from the server. If you are a designer, you have the right to complain and look for better solutions.
(The article assumes you have some knowledge of AJAX. If you are new to AJAX, just google for "Ajax" to get started.)
JSON To The Rescue
JSON is often pronounced as “JASON”. It stands for Javascript Object Notation and is a light weight way to describe hierarchical data. A lot of information on JSON can be found in the wikipedia and json.org. I often find the best way to learn is through examples. For the sake of simplicity, I will use one of the example found in wikipedia for explaination.
This is a typical JSON code returned from the server:
{ "firstName": "John", "lastName": "Smith", "address": { "city": "New York, NY", "zipCode": 10021, "street": "21 2nd Street" }, "phoneNumbers": [ "212 732-1234", "646 123-4567" ] }
In the code, “xxx” : ”yyy” is the key:value pair. In this case, “firstname” is the key and “John” is the value. “{ }” represents objects and “[ ]” represents arrays. So, “address” is a nested object and “phoneNumbers” is an array.
The code may look more complicated than its XML counterpart but the beauty of JSON lies in the way it can be decoded. In the browser, decoding JSON is a breeze.
// assuming http.responseText is the returned code from the server var response = eval("(" + http.responseText + ")"); if (response) { firstName = response.firstName; lastName = response.lastName; city = response.address.city; zipCode = response.address.zipCode; street = response.address.street; phoneNumbers1 = response.phoneNumbers[0]; phoneNumbers2 = response.phoneNumbers[1]; }
The variable “city” is within the “address” object, so to access the value of “city”, we use “response.address.city”. The 2 phone numbers are stored in the “phoneNumbers” array, so to access them, we have to use response.phoneNumbers[0] and so on...
If we wish to replace certain part of the webpage with the street address, we can do so easily using:
document.getElementById(‘some_id’).innerHTML = response.address.street;
As you can see, JSON is not hard to learn and very easy to implement in the webpages. If you haven’t been using JSON, you should start now!
Example: Updating A Form With JSON
The best way to learn anything is through examples. Imagine we have an online store in which members can login and purchase stuffs. Each member can have several shipment profiles. To make the checkout procedure more user friendly, we can use JSON to populate the shipment form when certain profile has been selected. The member can also make any last minute changes to the address before submitting the form.
|

|

|
| “A sample form – not filled” |
“form autofilled after one of the options is selected”
|
The HTML and the entire working example can be seen in the JSON form demo page
Each text field in the form has a unique name. To add AJAX functionality, we need to first create a http object like so in the Javascript:
function createRequestObject() { var req; if(window.XMLHttpRequest){ // Firefox, Safari, Opera... req = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Internet Explorer 5+ req = new ActiveXObject("Microsoft.XMLHTTP"); } else { alert('Problem creating the XMLHttpRequest object'); } return req; }
// Make the XMLHttpRequest object var http = createRequestObject();
When the user chooses an option in the select box, the “autoFill” function will be triggered. AJAX will now communicate with another php page via “get” (test_jason_server.php in this case). After processing the request, test_jason_server.php shoots back the JSON code to the browser. The code is then stored in the variable “http.responseText”.
function autoFill() { id = document.form.id.value; http.open('get', 'test_json_server.php?id='+id); http.onreadystatechange = function() { if(http.readyState == 4 && http.status == 200) { var response = eval("(" + http.responseText + ")"); if(response) { document.form.real_name.value= response.real_name; document.form.address.value= response.address; document.form.city.value= response.city; document.form.state.value= response.state; document.form.country.value= response.country; document.form.email.value= response.email; document.form.contact.value= response.contact; } } } http.send(null); }
The text fields in the form are now filled with new values from the server after simple manipulation with the “response” variable. The whole process takes place without the browser refreshing.
What Happens On The Server
This is the source code of test_json_server.php
// sent expired header to prevent browser from caching header("Expires: Mon, 01 Jan 1990 01:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")."GMT"); header("Cache-Control: no-cache, must-revalidate" ); header("Pragma: no-cache" ); header("Content-Type: text/xml; charset=utf-8");
// perform sql $sql = "SELECT * FROM address_table WHERE id='{$_GET['id']}'"; $rw = $db->getRow($sql); extract($rw);
// generate JSON $json = '{ "real_name": "'.$real_name.'", "address": "'.$address.'", "city": "'.$city.'", "state": "'.$state.'", "country": "'.$country.'", "email": "'.$email.'", "contact": "'.$contact.'" }'; echo $json; ?>
We need to do add some header settings before pushing the code back to the browser so as to prevent the browser from using the cache file. Alternatively, we can simply append a random number when sending the Ajax call. Data is then retrieved from the database via a simple select statement. We then format the JSON code and print it out. Simple, isn’t it?
What's Next?
In this article, I discussed the basics of JSON with a simple working demo. Instead of using splitting up the returned HTML using JSON, we could simply enclose the whole form with a DIV tag and make an AJAX call, then we refresh the content of the DIV with the returned HTML like so:
document.getElementById('formID').innerHTML = http.responseText
Hopefully, the code is easy enough to understand and can provide you a head start in using this cool technology especially if you are new to it. Now that the basics of JSON is covered, it is the time to mention another important piece of information - There is actually a lazier or (better way) to implement AJAX and JSON in your website. Just google for "AJAX toolkit" and you will know what I mean.
* You may test out the above example in the JSON form demo page. About The AuthorBernard Peh is a contract Web Developer based in Melbourne. He works with experienced web designers and developers everyday, designing and developing commercial websites.
|