HTML 5 TutorialsFetching Data with Ajax

Fetching Data with Ajax

Last time we understood the basics of Ajax. So, today we are going to learn how to fetch data using Ajax without refreshing the page or browser practically in the tutorial Fetching Data with Ajax.

In this practical with Ajax we are going to work with a web server. While running, there are some cases where the page won’t work on local machine; it needs a web server.
To work on server we can built our files on the local machine and then upload it in a sub directory created on the server.
In this tutorial we are going to use a Xampp server application.

So let’s start step by step.

  1. First download the Xampp server from the link https://www.apachefriends.org/download.html.
  2. Install the Xampp server.
  3. Start the Apache in the Xampp Control Panel as shown below:
  4. fig 1

    • You can see a red colour arrow showing a Stop button in front of the Apache Module. Actually this button has Start written on it initially and when you click it, it starts the Apache and changes its text from Start to Stop.
    • After starting the Apache close the Xampp Control Panel window.
    • Now your Xampp server is ready to run your webpages.
  5. Whenever you want to run your webpages or a website using Xampp server, you need to copy your website folder to htdocs folder located in xampp folder in your C drive.
  6. Now create a folder on desktop and name it as eduonix.
  7. Open a notepad++ document and save it as index.html in the eduonix folder just created on desktop.
  8. Now write the following code in index.html file and save it.
  9. <!DOCTYPE html>
    <html>
    <head>
    <title>Ajax Lesson</title>
    </head>
    <body>
    test the page
    </body>
    </html>
    
  10. The text test the page is written in the body section to just check the page.
  11. Now copy the eduonix folder and paste it in the htdocs folder which is in the xampp folder on C drive.
  12. Now next step is to open the browser and run the webpage. For this write the following address in the address bar of the browser:
  13. localhost/eduonix
    The index.html page in the eduonix folder will be shown with the text test the page.

  14. Here we finished testing the page. Now we want to create a div block containing some text and a button which when clicked will change the text in div block asynchronously.
  15. So replace the text test the page with the following code:
  16. <div id="data"><h2>Replace this text</h2></div>
    <button type="button" onclick="getDataFromXML()">Get Data</button>
    
    • Here, Replace this text is the statement that will be replaced asynchronously i.e. without page refresh and getDataFromXML() is the function called at the click event of the button to replace the text.
  17. Now as we have made changes replace the eduonix folder in the htdocs folder again with eduonix folder on desktop and then reload the browser, you will get the following output:
  18. div_&_button_output
    fig 2

    Actually we want to fetch data from a XML file, a simple text file and a JSON file asynchronously using AJAX in this Fetching Data with Ajax tutorial. So let’s start with a XML file.

    • First upload the movies.xml file created in previous tutorials to the eduonix folder inside htdocs folder.
  19. Now write the following code in the head section of index.html document in the
    <script>--</script>

    tag. We are now writing code for getDataFromXML() function.

  20. <script>
    function getDataFromXML()
    {
       var xmlhttp;
       if(window.XMLHttpRequest)
       {
    	xmlhttp=new XMLHttpRequest();
       }
       else
       {
    	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.onreadystatechange=function()
       {
          if(xmlhttp.readyState==4 && xmlhttp.status==200)
          {
             xmldata=xmlhttp.responseXML;  //retrieve result as a XML object
    	 var movies=xmldata.getElementsByTagName('movie');
    			
    	 var output="";
    	 output+=movies[0].getElementsByTagName('title')[0].firstChild.nodeValue;
    	 document.getElementById("data").innerHTML=output;
          }
       }
       xmlhttp.open("GET","movies.xml",true);
       xmlhttp.send();
    }
    </script>
    

    Description of the function:

    • Here, getDataFromXML() function is defined to replace the text on the webpage with the data in the movies.xml file asynchronously.
    • A variable xmlhttp is declared for the XMLHttp object.
    • Next the XMLHttpRequest object is created to send the request to the server. But some browsers like IE6 and lower versions of IE do not support XMLHttp object, so they require creating ActiveXObject for sending the request. This is done by using the following code:
    • if(window.XMLHttpRequest)
      {
      	xmlhttp=new XMLHttpRequest();
      }
      else
      {
      	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      
    • The else part in above code is for lower versions of IE browser.
    • Now after creating the request object and sending the request, we need to check whether our request has been processed or not. For this we need to check the readyState and status properties of XMLHttpRequest object. The code is as follows:
    • xmlhttp.onreadystatechange=function()
      {
         if(xmlhttp.readyState==4 && xmlhttp.status==200)
         {
      	xmldata=xmlhttp.responseXML;
      	var movies=xmldata.getElementsByTagName('movie');
      	var output="";
      	output+=movies[0].getElementsByTagName('title')[0].firstChild.nodeValue;
      	document.getElementById("data").innerHTML=output;
         }
      }
      
    • Here, in the above code onreadystatechange is the event that occurs when the request is being processed.
    • It is assigned a function that checks the readyState ad status properties.
    • In the if statement the readyState is equated to 4 and status is equated to 200 because 4 indicate that request finished and response is ready and 200 indicates that the status is OK.
    • If this if statement is satisfied, the XML response object is assigned to xmldatavariable as shown below:
    • xmldata=xmlhttp.responseXML;
    • After this a variable movies is declared which is assigned an element retrieved from xmldata by the tag name.
    • Then a variable output is declared to store the output.
    • Next the title of the first movie is assigned to the output using the following statement:
    • output+=movies[0].getElementsByTagName('title')[0].firstChild.nodeValue;
    • Next it is displayed in the browser window.
    • Here, we have printed only one movie title, the output is shown below:
    • output_of_single_movie_title_in_XML
      fig 3

    • If we want all the movie titles to be displayed, then we should do it in a loop. Follow the following code to display all the movie titles:
    • if(xmlhttp.readyState==4 && xmlhttp.status==200)
      {
         xmldata=xmlhttp.responseXML;
         var movies=xmldata.getElementsByTagName('movie');
      
         var output='<ul>';
         //output+=movies[0].getElementsByTagName('title')[0].firstChild.nodeValue;
      			
         for(i=0;i<movies.length;i++)
         {
      	output+='<li>'+movies[i].getElementsByTagName('title')[0].firstChild.nodeValue+'</li>';
         }
         output+='</ul>'
         document.getElementById("data").innerHTML=output;
      }
      
    • Here, we have put the movie titles in the un-ordered list and have put the statement to retrieve movie titles in a for loop so that all the titles are added up to the variable output.
    • Next outside for loop, the variable output is printed.
    • The output is shown below:
    • displaying_all_movie_titles_from_XML_file
      fig 4

    • Now next thing is to just get the data and send the response to the client. The code for it is as follows:
    • xmlhttp.open("GET","movies.xml",true);
      xmlhttp.send();
      
    • We know that the data to be send in response is in the movies.xml file, so we specify the details in the statement xmlhttp.open(“GET”,”movies.xml”,true);
    • Here, GET is the method to be used for sending the data. We can use POST method also.
    • The data to be send is in the movies.xml file so it is specified as the second value of the open method.
    • The third value of open method is true which indicates that the response should be sent asynchronously.
    • Next the response is sent through statement xmlhttp.send().
    • We finished sending the text, the output is shown as shown in fig 4.
  21. Now we will see how to replace the div block text with plain text. So create a new text file and name it as data.txt. Write the following text in the file and save it.
  22. This text is from the data.txt file.

  23. The procedure is same as the XML file, just a slight change. The code for getDataFromText() function is written in the
    <script>--</script>

    tag:

  24. function getDataFromText()
    {
       var xmlhttp;
       if(window.XMLHttpRequest)
       {
    	xmlhttp=new XMLHttpRequest();
       }
       else
       {
    	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
       }
    	xmlhttp.onreadystatechange=function()
    	{
     	   if(xmlhttp.readyState==4 && xmlhttp.status==200)
    	   {
    		document.getElementById('data').innerHTML=xmlhttp.responseText;
    	   }
    	}
    	xmlhttp.open("GET","data.txt",true);
    	xmlhttp.send();
    }

    Description of the function

    • Here, everything is same as done in the getDataFromXML function.
    • Only the if block checking the readyState and status properties have the following statement that executes when the condition satisfies:
    • document.getElementById('data').innerHTML=xmlhttp.responseText;
    • This statement selects the div block with its id data and replaces its actual text with the response text using the statement innerHTML.
    • And xmlhttp.responseText is the response object that contains response in the plain text format.
    • The response is fetched from data.txt file, so it is specified in the statement shown below:
    • xmlhttp.open("GET","data.txt",true);
    • Call the function getDataFromText()at the onclick event of the button Get Data as shown below.
    • <div id="data"><h2>Replace this text</h2></div>
      <button type="button" onclick="getDataFromText()">Get Data</button>
    • The output that we get on clicking on the Get Data button is shown below:
    • output_of_plain_text
      fig 5

  25. Now next we will deal with JSON. We had created a JSON file in previous tutorials named movies.json. Upload this file in the eduonix folder located in the htdocs file in xampp folder.
  26. Write the following function in order to replace the div block text with the data present in the movies.json file in the head section inside
    <script>--</script>

    tags.

  27. function getDataFromJSON()
    {
       var xmlhttp;
       if(window.XMLHttpRequest)
       {
    	xmlhttp=new XMLHttpRequest();
       }
       else
       {
    	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.onreadystatechange=function()
       { 
    	if(xmlhttp.readyState==4 && xmlhttp.status==200)
    	{
    	   var jsondata=JSON.parse(xmlhttp.responseText); //retrieve result as a javascript object
    			
    	   var movies=jsondata.movies;
    	   var output='<ul>';
    			
    	   for(i=0;i<movies.length;i++)
    	   {
    		output+='<li>'+movies[i].title+'<li>';
    	   }
    	   output+='</ul>'
    			
    	   document.getElementById('data').innerHTML=output;
    	}
       }
       xmlhttp.open("GET","movies.json",true);
       xmlhttp.send();
    }

    Description of the function

    • Here also the rest of the part is same, only there is slight difference in the retrieving of the output.
    • Let us understand the code executed when the if condition checking readyState and status properties is satisfied:
    • The code is shown below:
    • if(xmlhttp.readyState==4 && xmlhttp.status==200)
      {
         var jsondata=JSON.parse(xmlhttp.responseText); //retrieve the result in JSON format
      			
         var movies=jsondata.movies;
         var output='<ul>';
      		
         for(i=0;i<movies.length;i++)
         {
      	output+='<li>'+movies[i].title+'<li>';
         }
         output+='</ul>'
         document.getElementById('data').innerHTML=output;
      }
      
    • Here, a variable jsondata is declared to store the response. It is assigned with the response object.
    • We don’t have direct method to retrieve the JSON response object hence the xmlhttp.responseText is converted to JSON using the following statement:
    • var jsondata=JSON.parse(xmlhttp.responseText);
    • Next we have retrieved movies array from jsondata object and stored it in movies variable.
    • And then displayed the movie titles in for loop using statement
    • output+='<li>'+movies[i].title+'<li>';
    • Here we have just used movies[i].title to retrieve the movie title which is very easy as compared to XML. Hence JSON is more popular than XML.
    • Next the output is printed using statement
    • document.getElementById('data').innerHTML=output;
    • One more thing, you have to add your movies.json file name to the response to be send as shown below:
    • xmlhttp.open("GET","movies.json",true);
    • Now call getDataFromJSON() function at the onclick event of the button GET DATA as shown below:
    • <div id="data"><h2>Replace this text</h2></div>
      <button type="button" onclick="getDataFromJSON()">Get Data</button>
    • The output of the data fetched and displayed in the div block is shown below:
    • displaying_all_movie_titles_from_JSON_file
      fig 6

    • Here you can notice that whatever we have fetched using Ajax, may it be a plain text, a XML data or JSON; it is fetched asynchronously i.e. without refreshing the page.

Thus in this tutorial we learned Fetching Data with Ajax.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -