AJAX Example 4- Asynchronous Communication with XML using AJAX

//Program demonstrating asynchronous communication with an XML File using AJAX

Ajax4XML.html


<html>
<head>
<title>Ajax4 XML Example</title>
<script type="text/javascript">

var xmlhttp;

if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

function loadXMLDoc()
{
	var txt,first,i;

	if(xmlhttp){
	xmlhttp.open("GET","employee_data.xml",true);
	xmlhttp.onreadystatechange=function() {
	  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
		var xmlDoc=xmlhttp.responseXML;
		txt="";
		first=xmlDoc.getElementsByTagName("first");
		for (i=0;i<first.length;i++) {
		  txt=txt + first[i].childNodes[0].nodeValue + "<br />";
		 }
		document.getElementById("myDiv").innerHTML=txt;
		}
	  }

	  xmlhttp.send(null);
	}
}//function end
</script>
</head>

<body>

<h2>Employee Data</h2>
<div id="myDiv"></div>
<br />
<button type="button" onclick="loadXMLDoc()">Get Employee Names</button>

</body>
</html>

employee_data.xml

<?xml version="1.0" encoding="UTF-8"?>

<employees>
	<employee position="manager">
		<name>
			<first>Meenakshi</first>
			<last>Das</last>
		</name>
		<age>31</age>
	</employee>
	<employee position="developer">
		<name>
			<first>Dia</first>
			<last>Agarwal</last>
		</name>
		<age>25</age>
	</employee>
	<employee position="developer">
		<name>
			<first>Natalie</first>
			<last>Abraham</last>
		</name>
		<age>23</age>
	</employee>
	<employee position="engineer">
		<name>
			<first>Kim</first>
			<last>Gentile</last>
		</name>
		<age>22</age>
	</employee>
	<employee position="accountant">
		<name>
			<first>Ankita</first>
			<last>Adhikary</last>
		</name>
		<age>25</age>
	</employee>
	<employee position="developer">
		<name>
			<first>Priya</first>
			<last>Kapoor</last>
		</name>
		<age>32</age>
	</employee>
</employees>

Snapshot of the o/p

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s