How to Load Content from XML, JSON, Text File by jQuery AJAX

arp14 AJAX, JavaScript, jQuery, Tutorial Tags: , , , , , , , , 32

Hi guys, in this tutorial we are going to learn, how to load / parse content from XML, JSON and Text Files into a simple web page by regular AJAX and jQuery AJAX. You can also see Basics of AJAX Online Tutorial if you are new to AJAX technologies. For this tutorial, you should have a minimum knowledge on JavaScript, XML and JSON is optional if you want to work with JSON data. You also need to know jQuery to work with jQuery AJAX.

Load XML, JSON, Text File by jQuery AJAX

Load / Parse XML File using Regular AJAX

Required Files

Index.html

<html>
	<head><title>How to Load Content from XML File using AJAX</title></head>
	<body>
		<h1>How to Load Content from XML File using AJAX</h1>
		<div id='update'>This is a div. This will be updated with Contents from xml file using AJAX.</div>
		<script src="script.js"></script>
	</body>
</html>

Data.xml

<cats>
    <cat id='1'>
        <name>George</name>
        <gender>male</gender>
        <color>white-mustard</color>
        <age>5 years</age>
    </cat>
    <cat id='2'>
        <name>Pety</name>
        <gender>female</gender>
        <color>white-black-mustard</color>
        <age>3</age>
    </cat>
    <cat id='3'>
        <name>Alex</name>
        <gender>male</gender>
        <color>white-grey-black</color>
        <age>3</age>
    </cat>
    <cat id='4'>
        <name>Rex</name>
        <gender>male</gender>
        <color>white-mustard</color>
        <age>2</age>
    </cat>
</cats>

 

Script.js

var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); 		// all browsers except IE
else xhr = new ActiveXObject("Microsoft.XMLHTTP"); 		// for IE

xhr.open('GET', 'data.xml', false);
xhr.onreadystatechange = function () {
	if (xhr.readyState===4 && xhr.status===200) {			
		var items = xhr.responseXML.getElementsByTagName('name');
		var output = '<ul>';
		for (var i=0; i<items.length; i++) output += '<li>' + items[i].firstChild.nodeValue + '</li>';
		output += '</ul>';

		var div = document.getElementById('update');
		div.innerHTML = output;
	}
}
xhr.send();

 

Explaination

In this script above, we used responseXML property to get response XML data. Then we search and get data from “name” tag in the XML file – using getElementsByTagName() function. For some nice presentation, we used unordered list to print it on the screen. We also looped the returned “items” array data by a simple for loop and concatenate list items in “output” variable. ‘items[i]” is each parent tag and “firstChild” is to get the first child tag and then “nodeValue” gets the value within the tag. After all these we get the div with ID=”update” and replace it’s inner HTML content using “innerHTML” function.


 

Load / Parse JSON File using Regular AJAX

Required Files

Index.html

<html>
	<head><title>How to Load Content from JSON File using AJAX</title></head>
	<body>
		<h1>How to Load Content from JSON File using AJAX</h1>
		<div id='update'>This is a div. This will be updated with Contents from JSON file using AJAX.</div>
		<script src="script.js"></script>
	</body>
</html>

Data.json

[
	{
		"name" 		: "George",
		"gender" 	: "male",
		"color" 	: "white-mustard",
		"age" 		: "5 years"
	},
	{
		"name" 		: "Pety",
		"gender" 	: "female",
		"color" 	: "white-black-mustard",
		"age" 		: "3 years"
	},
	{
		"name" 		: "Alex",
		"gender" 	: "male",
		"color" 	: "white-grey-black",
		"age" 		: "3 years"
	},
	{
		"name" 		: "Rex",
		"gender" 	: "male",
		"color" 	: "white-mustard",
		"age" 		: "2 years"
	}
]

Script.js

var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); 		// all browsers except IE
else xhr = new ActiveXObject("Microsoft.XMLHTTP"); 		// for IE

xhr.open('GET', 'data.json', false);
xhr.onreadystatechange = function () {
	if (xhr.readyState===4 && xhr.status===200) {			
		var items = JSON.parse(xhr.responseText);
		var output = '<ul>';
		for (var key in items) {
			output += '<li>' + items[key].name + '</li>';
		}
		output += '</ul>';
		document.getElementById('update').innerHTML = output;
	}
}
xhr.send();

Explanation

This script is very similar to the previous one. Now we get “data.json” file instead of “data.xml” file. The returned data is nothing but plain text with a particular format called JSON (javascript object notation). We passed the response text to “JSON.parse()” function to fetch JSON data. Rest part of the script is about same except we used “items[key].name” to get returned data.


 

Load / Parse Text File using Regular AJAX

Required Files

Index.html

<html>
	<head><title>How to Load Content from Text File using AJAX</title></head>
	<body>
		<h1>How to Load Content from JSON File using AJAX</h1>
		<div id='update'>This is a div. This will be updated with Contents from xml file by AJAX.</div>
		<script src="script.js"></script>
	</body>
</html>

Data.txt

George
Pety
Alex
Rex

Script.js

var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); 		// all browsers except IE
else xhr = new ActiveXObject("Microsoft.XMLHTTP"); 		// for IE

xhr.open('GET', 'data.txt', false);
xhr.onreadystatechange = function () {
	if (xhr.readyState===4 && xhr.status===200) {
		var div = document.getElementById('update');
		div.innerHTML = xhr.responseText;
	}
}
xhr.send();

Explanation

This is nearly same like above two scripts. This time we get “data.txt” file. Now, we just get the response text and put it in the div with ID=”update” using “innerHTML” function. This is actually so simple, isn’t it?


 

Load / Parse XML File using jQuery AJAX

You know the power of jQuery, it does what it says – “Write less – do more!”. Using jQuery can be extremely beneficial while handling AJAX requests.

Required Files

Index.html

<html>
	<head>
		<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
		<script type="text/javascript" src="script.js"></script>
		<title>Load Content from JSON File using jQuery AJAX - Example</title>
	</head>
	<body>
		<h1>Load Content from XML File using jQuery AJAX - Example</h1>
		<div id='update'>This is a div. This will be updated with Contents from XML file by jQuery AJAX.</div>
	</body>
</html>

Data.xml

This is the same XML file used in previous example.

Script.js

$(document).ready(function () { // load xml file using jquery ajax
    $.ajax({
        type: "GET",
        url: "data.xml",
        dataType: "xml",
        success: function(xml) {
            var output = '<ul>';
            $(xml).find('cat').each(function(){
                var name = $(this).find('name').text();
                var id = $(this).attr('id');
                output += '<li>' + name + ' (' + id + ')</li>';
            });
            output += '<ul>';
            $('#update').html(output);
        }
    });
});

 

Explanation

At first, we loaded jQuery library in the head tag of the HTML file. We used “$.ajax()” function to get the XML file with “type: GET” property. We provided the XML file URL, data type. On success it runs a standalone function as callback. It has a parameter named “xml” to pass the data within the function. Then we find the tags by “.find()” function and then called “$.each()” function to get each tag of returned data. “$.each()” function calls a standalone function. We use “.text” to grab each name tag of each cat tag. We also get attribute of each cat tags with “attr()” function. Finally we update content of the div ID=”update” with the processed data.


 

Load / Parse JSON File using jQuery AJAX

Required Files

Index.html

<html>
	<head>
		<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
		<script type="text/javascript" src="script.js"></script>
		<title>Load Content from JSON File using jQuery AJAX - Example</title>
	</head>
	<body>
		<h1>Load Content from JSON File using jQuery AJAX - Example</h1>
		<div id='update'>This is a div. This will be updated with Contents from JSON file by jQuery AJAX.</div>
	</body>
</html>

Data.json

This is the same JSON file used in previous example.

Script.js

$(document).ready(function () { // load json file using jquery ajax
	$.getJSON('data.json', function (data) {
		var output = '<ul>';
		$.each(data, function (key, val) {
			output += '<li>' + val.name + '</li>';
		});
		output += '</ul>';
		$('#update').html(output); 	// replace all existing content
	});
});

Explanation

At first, we loaded jQuery library in the head tag of the HTML file. We used “$.getJSON()” function to get the JSON file. File URL is the first argument and a standalone function as callback is second. It has a parameter named “data” to pass the data within the function. Then we called “$.each()” function to get each data block of returned data. “$.each()” function takes “data” and a standalone function with two parameters (key, value pair) and now we can use the key and value. We use “.name” to get key or value name. Finally we update content of the div ID=”update” with the processed data.


 

Load / Parse Text File using jQuery AJAX

Required Files

Index.html

<html>
	<head>
		<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
		<script type="text/javascript" src="script.js"></script>
		<title>Load Content from JSON File using jQuery AJAX - Example</title>
	</head>
	<body>
		<h1>Load Content from Text File using jQuery AJAX - Example</h1>
		<div id='update'>This is a div. This will be updated with Contents from Text file by jQuery AJAX.</div>
	</body>
</html>

Data.json

This is the same Text file used in previous example.

Script.js

$(document).ready(function () {       // load text file using jquery ajax
    $('#update').load('data.txt');    // load text data
});

Explanation

At first, we loaded jQuery library in the head tag of the HTML file. We used “$.load()” function to get the Text file. It took the file url as parameter. We update content of the div ID=”update” directly from “$.load()” function.

It is so fun to work with AJAX. I hope this article will help you to get stuffs that you want. You can download all sample files from here: http://www.4shared.com/zip/Qlf7VQy2/JavaScript_and_jQuery_AJAX.html

useful link: http://api.jquery.com/jQuery.ajax/

If you have any problem regarding Regular AJAX or jQuery AJAX, please comment below – I will be back to you.

Thank you!

32 thoughts on “How to Load Content from XML, JSON, Text File by jQuery AJAX

          1. Are you directly opening the files by doubleclicking? If yes, it won’t work.
            A web server must be installed in your machine to make AJAX XHR (XmlHttpRequest) working.
            Install WAMP Server first, then place all files in “www” directory in wamp installation folder. After that, open those files from your localhost (http://localhost/).
            (for other OS users, there’re MAMP, XAMP available – google it)

  1. Hi Arpan, I like your tutorial, though I have had a few problems.. Firstly I can make your code work if I use the script, but if I try to put an external .xml file in the script all I get is dots.. If I copy and paste the external file and use it for data.xml I only get name and nothing else.. I think its down to the face name on my xml list is not the parent.. the list goes then .. is what I want to use though there is no info attached to that and it looks the parent.. I just get dots if I try that.. I like the script its simple and easy to use, if I could just crack this bit.. Its a little bit like slider scripts I have used with jquery before.. This is the external xml http://www.digitalselect-uk.com/psychic/xml/profiles any clues would help as I have been on this for days.. I need to create css as well to rap the output, but for now I just need to get it to work..

    1. Hi swasuk,

      Here is how to fetch the xml:

      $(document).ready(function () { // load xml file using jquery ajax
      	$.ajax({
      		type: "GET",
      		url: "profiles.xml",
      		dataType: "xml",
      		success: function(xml) {
      			var output = '<table>';
      			$(xml).find('reader').each(function(){
      				var name = $(this).find('name').text();
      				var status = $(this).find('status').text();
      				var pin = $(this).find('pin').text();
      				var picture = $(this).find('picture').text();
      				var description = $(this).find('description').text();
      				var skill = $(this).find('category skill').text();
      				var tool = $(this).find('category tool').text();
      				var subject = $(this).find('category subject').text();
      				
      				output += '<tr>';
      				output += '<td>' + name + '</td>';
      				output += '<td>' + status + '</td>';
      				output += '<td>' + pin + '</td>';
      				output += '<td>' + picture + '</td>';
      				output += '<td>' + description + '</td>';
      				output += '<td>' + skill + '</td>';
      				output += '<td>' + tool + '</td>';
      				output += '<td>' + subject + '</td>';
      				output += '</tr>';
      			});
      			output += '</table>';
      			$('#update').html(output);
      		}
      	});
      });
      

      This was the first part of your problem.
      But the second part is the cross domain issue. For cross domain issue, try this http://jquery-howto.blogspot.de/2013/09/jquery-cross-domain-ajax-request.html or this http://www.ajax-cross-domain.com/ and let me know.

  2. Hi thanks for the reply.. I can’t seem to get it to work.. I am using the first code and pulling it in with the php.. with TITLE HERE my js file is name readers.js and the file I am trying to display it on is readers.php

  3. I am testing with local xml, I have copied the external file to test.. I am using the Load / Parse XML File using Regular AJAX method.. So basically I amended the .js file only to put your code in, and nothing happened.. so thats showing it on the page the div is on..

    1. Yes, very messy as these are raw data – you have to format it as how you want – its up to you as your needs.
      You got the URL of pictures, thats all. To show pictures, set the image URL you got from XML to src attribute of img tags – its plain HTML.
      Example:
      change
      output += ‘<td>’ + picture + ‘</td>’;
      to
      output += ‘<td><img scr=”‘ + picture + ‘” /></td>’;

  4. Hi I got it working though still not sorted through the external .xml I played with the code you gave me to align things better.. Anyway you can see it at work on this page http://psychiclive.eu I need to put it in a better scroller than the iframe I used to test.. but I managed to get css to work around the different elements by adding div calls around the table elements you just described in your example.. Thanks Arpan.. I owe you one.. I will tweet this post from some of my accounts..

  5. Hi Arpan,
    Can u teach me how to parsing data files from external url via javascript? I mean I want to post data from domain A to domain B with some parameter like this,
    domain A = _http://domain-A.com/parsing.php?id=1234
    I really appreciated if you want to help me. Thnaks.

  6. Hi Arpan, can you please contact me on the form connected to the link on this.. I could do with some help with the xml feed you helped me with some months ago..

  7. Hi Arpan,

    I am very noob in jquery and ajax, saw your examples, very useful and interesting. I am trying this to one of my site. But I am facing the cross domain issue and not able to resolve it and badly need your help. Can you explain or implement the example by calling the same xml from another domain. That would really help me a lot and it would be a lifesaver.

  8. Hola Arpan,

    Tengo un problema al cargar un File.txt en un Div , lo hago usando el metodo que mencionaste:
    $(‘#update’).load(‘data.txt’);

    Mi problema es con el formato del texto, ya si logro cargarlo pero me muestra todo el texto junto, existe alguna forma de darle formato o que respete el formato que tiene el file.txt?

    Gracias

  9. Really like the example “Load / Parse JSON File using Regular AJAX”. Can you show a script that reads each item in the Data.xml as a separate UL list with it’s subitems?

Leave a Reply

Note: Your email address will not be published. Required fields are marked *