Learn Json

Json With Ajax

In this chapter we will retrieve json file using Ajax.we will use following step to retrieve json file.

Example

Step 1

Firstly we will create json file data.json with following code.

{"First_Name": "Bunny", "Last_Name": "Lasker"} Step 2

Now We will create a Javascript file json.js with following code.

function getXMLHTTP() { //fuction to return the xml http object
    var xmlhttp=false;  
    try{
      xmlhttp=new XMLHttpRequest();
    }
    catch(e)  {   
      try{      
        xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e){
        try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e1){
          xmlhttp=false;
        }
      }
    }
      
    return xmlhttp;
  }

function loadJSON()
{
   var req = getXMLHTTP();
     
   var data_file = "data.json";         
    
    if (req) {
 req.onreadystatechange = function() {
        if (req.readyState == 4) {
      
        if (req.status == 200) {
      var jsonObj = JSON.parse(req.responseText);
        // jsonObj variable now contains the data structure and can
        // be accessed as jsonObj.name and jsonObj.country.
        document.getElementById("fname").innerHTML =  jsonObj.First_Name;
        document.getElementById("lname").innerHTML = jsonObj.Last_Name;
            
         } 
          else {
          
            alert("There was a problem while using XMLHTTP:\n" + req.statusText);
          }
        
        }       
      }     
      req.open("GET", data_file, true);
      req.send(null);
    }     
}
Step 3

In Last step we will create a html file json.html with following code.

<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<script src="json.js"> </script>
<title>Json With Ajax</title>
</head>
<body>
<h1>Employee Detail</h1>
<table class="src">
<tr><th>First Name</th><th>Last Name</th></tr>
<tr><td><div id="fname">Manish</div></td>
<td><div id="lname">Mishra</div></td></tr>
</table>
<div class="central">
<button type="button" onclick="loadJSON()">Update Details </button>
</body>
</html>