Falcon80 Logo
JSON and AJAX

We now know that a JSON object can be directly assigned to a javascript variable. But why would we want to do it? This page explains some applications for the feature.

AJAX stands for Asynchronouse Javascript. It is part of javascript and allows a developer to update only certain parts of a webpage without having to refreash the whole page. Websites updating sports scores are a good example of AJAX. If these scores have to be updated on the website, obviously, they must be stored somewhere on the server so that the webpage can retrieve the score. This is where JSON comes in. Any data that is updated using AJAX can be stored using the JSON format on the web server. By using AJAX, javascript can retrieve these JSON files when necessary, parse them and then do one of two things.

* Store the parsed values in variables for further processing before displaying them on the webpage and/or
* Directly assign the data to the DOM elements in the webpage, so that it gets displayed on the site.

Consider the following javascript code:


<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">

<script type="application/javascript">

function loadJSON()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

// Parse the JSON data structure contained in xmlhttp.responseText using the JSON.parse function.
var JSONObject = JSON.parse(xmlhttp.responseText);

// The JSONObject variable now contains the data structure and can be accessed as JSONObject.firstName and
// JSONObject.lastName. Assign the object members to the DOM elements FirstName and LastName so that they get
// displayed on the page
document.getElementById("FirstName").innerHTML = JSONObject.firstName;
document.getElementById("LastName").innerHTML = JSONObject.lastName;
}
}
xmlhttp.open("GET","JSON.txt",true);
xmlhttp.send();
}
</script>

<title>JSON and AJAX</title>
</head>
<body>
<div id="FirstName">Prince</div>
<div id="LastName">Vivian</div>
<button type="button" onclick="loadJSON()">Update Name</button>
<h2>Click this button to update the page</h2>
</body>
</html>



Note:
To try out the above example, copy the code into a notepad and save it as a .html file. Create another blank file and save it as JSON.txt. Copy the following data structure into the JSON.txt file:

{"firstName": "Isabelle", "lastName": "Solomon"}

Add both files to your webserver folder. Open the .html file from a browser. You should see the following:

Prince
Vivian

Click this button to update the page

When you click on the 'Update Name' button, the first name and last name should get updated to 'Blaise' and 'Pascal' respectively.