Javascript - Read XML file from file server through XMLHttpRequest

Here is the code for getting xml from server side and navigation,reading that xml through javascript.
Below is an server side xml(xml must be in same folder or give the exact path of xml in xmlhttp.open method) and javascript code that read xml through xmlhttp object after request processed and response is ready (ready state 4) then read the city tag of xml and bind it to dropdown (ddlcity)

ReadyState  Description
0      The request is not initialized
1      The request has been set up
2      The request has been sent
3      The request is in process
4      The request is complete


Server Side Xml Named   City_Mall.Xml 

< ?xml version="1.0" encoding="UTF-8" ?>
    <cityname>
      <City>Agra</City>
      <City>Ahmedabad</City>
      <City>Amritsar</City>
      <City>Aurangabad</City>
      <City>Bangalore</City>
      <City>Bhubaneswar</City>
      <City>Bilaspur</City>
      <City>Calicut</City>
      <City>Chandigarh</City>
      <City>Chennai</City>
      <City>Coimbatore (Kovai)</City>
      <City>Dhanbad</City>
    </cityname>


JavaScript to Read Xml asynchronously

<script type="text/javascript">
  function BindCity() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        //xmlhttp.readyState == 4 (0-4 request processed and responce is ready)
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var x =      xmlhttp.responseXML.documentElement.getElementsByTagName('city');
            var nList = document.getElementById('ddlcity');
            for (i = 0; i < x.length; i++) {
                var nOption = document.createElement('option');
                var vCity = x[i].getAttribute('name');
                //or x[i].firstChild.nodeValue --text node(first child)
                nOption.appendChild(document.createTextNode(vCity));
                nOption.setAttribute("value", vCity);
                nList.appendChild(nOption);
            }
        }
    }
    xmlhttp.open("GET", 'City_Mall.xml', true);
    xmlhttp.send();
    }
</script>


Popular Posts