Categories:

Retrieving a JSON file using Ajax

JSON has become another popular way to store data in a structured way after XML. With JSON, you use JavaScript's array and object literals syntax to define data inside a text file in a way that can be returned as a JavaScript object using eval(). Here's the same information contained inside the sample XML file earlier, but specified using JSON syntax instead (lets name it "javascriptkit.json"):

{
title: "javascriptkit.com",
link: "http://www.javascriptkit.com",
description: "JavaScript tutorials and over 400+ free scripts!",
language: "en",
items: [
{
title: "Document Text Resizer",
link: "http://www.javascriptkit.com/script/script2/doctextresizer.shtml",
description: "This script adds the ability for your users to toggle your webpage's font size, with persistent cookies then used to remember the setting"
},
{
title: "JavaScript Reference- Keyboard/ Mouse Buttons Events",
link: "http://www.javascriptkit.com/jsref/eventkeyboardmouse.shtml",
description: "The latest update to our JS Reference takes a hard look at keyboard and mouse button events in JavaScript, including the unicode value of each key."
},
{
title: "Dynamically loading an external JavaScript or CSS file",
link: "http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml",
description: "External JavaScript or CSS files do not always have to be synchronously loaded as part of the page, but dynamically as well. In this tutorial, see how."
}
]

}

Note that there are many ways to interpret the data in a XML file for translation, so the JSON equivilant above is just one version. Using JSON to store data always begins with a main curly braces {} without a variable name assignment. The data you wish to store is then done inside either JS object literals or arrays. The actual data can be anything from text to JavaScript variables, objects or functions, anything that are valid JavaScript assignments.

JSON and XML files are both just plain text files. Unlike XML files, however, the browser currently doesn't provide a way to natively return a JSON file as a JavaScript object (unlike "request.responseXML" with XML for example). However, the use of eval() on "request.responseText" does the trick just fine, and is the key to using Ajax with JSON files:

<div id="result"> </div>

<script type="text/javascript">

function ajaxRequest(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
    //suppress error
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  return new XMLHttpRequest()
 else
  return false
}


var mygetrequest=new ajaxRequest()
mygetrequest.onreadystatechange=function(){
 if (mygetrequest.readyState==4){
  if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
   var jsondata=eval("("+mygetrequest.responseText+")") //retrieve result as an JavaScript object
   var rssentries=jsondata.items
   var output='<ul>'
   for (var i=0; i<rssentries.length; i++){
    output+='<li>'
    output+='<a href="'+rssentries[i].link+'">'
    output+=rssentries[i].title+'</a>'
    output+='</li>'
   }
   output+='</ul>'
   document.getElementById("result").innerHTML=output
  }
  else{
   alert("An error has occured making the request")
  }
 }
}

mygetrequest.open("GET", "javascriptkit.json", true)
mygetrequest.send(null)

</script>

Demo:

The key points to remember when fetching a JSON text file as a JavaScript object are:

  • Retrieve the file as plain text using "response.responseText", then use eval() on it to turn the JSON valid text file into a JavaScript object.
  • Notice how a parenthesis surrounds the statement to evalulate so it's actually "(response.responseText)" This is necessary to turn the statement into an expression, so eval() can evaluate it instead of JavaScript executing the statement instead.
  • The result is a custom JavaScript object, with which you access its various properties using the standard "dot" notation.

One thing worth mentioning about using Ajax to fetch a JSON file is the potential security risks, due to the use of eval(). This is normally a non issue for local JSON files where you have complete control and knowledge over what's contained in them. For cross domain Ajax with JSON however, it's important to make sure beforehand that there isn't any thing malicious in the target JSON file that can be bought to life through the eval() method. There are JSON parsers that will handle for you such security concerns, such as: http://www.json.org/js.html

End of Tutorial