AJAX XML EXAMPLE

Given the following XML file with contact data

File “contacts.xml”

<Contacts> <Contact> <firstName>Bob</firstName> <lastName>Dylan</lastName> <age>25</age> </Contact> <Contact> <firstName>Bob</firstName> <lastName>Dylan</lastName> <age>25</age> </Contact> <Contact> <firstName>Bob</firstName> <lastName>Dylan</lastName> <age>25</age> </Contact> <Contact> <firstName>Bob</firstName> <lastName>Dylan</lastName> <age>25</age> </Contact> <Contact> <firstName>Bob</firstName> <lastName>Dylan</lastName> <age>25</age> </Contact> <Contact> <firstName>Bob</firstName> <lastName>Dylan</lastName> <age>25</age> </Contact> </Contacts>

Website "show.htm" showing part of the information gathered from the previous XML file.

File "show.htm"

<!DOCTYPE html> <html> <head> <script> function loadXMLData(url) { var xmlhttp; var txt,ele,dat,i; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { txt="<table border='1'><tr><th>lastName</th><th>Age</th></tr>"; ele=xmlhttp.responseXML.documentElement.getElementsByTagName("Contact"); for (i=0;i<ele.length;i++) { txt=txt + "<tr>"; dat=ele[i].getElementsByTagName("lastName"); { try { txt=txt + "<td>" + dat[0].firstChild.nodeValue + "</td>"; } catch (er) { txt=txt + "<td> </td>"; } } dat=ele[i].getElementsByTagName("age"); { try { txt=txt + "<td>" + dat[0].firstChild.nodeValue + "</td>"; } catch (er) { txt=txt + "<td> </td>"; } } txt=txt + "</tr>"; } txt=txt + "</table>"; document.getElementById('infoContacts').innerHTML=txt; } } xmlhttp.open("GET",url,true); xmlhttp.send(); } </script> </head> <body> <h1>Contacts</h1> <button onclick="loadXMLData('contacts.xml')">Get contacts info</button> <div id="infoContacts"></div> </body> </html>