Ajax Server Response



In the previous tutorial we have also seen the methods that we use to send request to a server. In this tutorial we will be learning the different ways, how we get response from the server.

Depending on the type of response we get from the server it is categorized in two parts.

ajax response type
To get response from a server we can use following properties –

Property Description
responseText get the response data as a string
responseXML get the response data as XML data

The responseText Property :

Consider following Example :

<!DOCTYPE html>
<html>
<head>
<script>
function loadAjaxData()
{
   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() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
     document.getElementById("div1").innerHTML = xmlhttp.responseText;
    }
   }
   xmlhttp.open("GET","info.txt",true);
   xmlhttp.send();
}
</script>
</head>
<body>

<div id="div1"><h2>Display Title</h2></div>
<button type="button" onclick="loadAjaxData()">Change Title</button>

</body>
</html>

If the response from the server is not XML, use the responseText property.

document.getElementById("dataDiv").innerHTML=xmlhttp.responseText;

Above xmlhttp.responseText property will contain the non-XML response. responseText property will return a string.

The responseXML Property :

Suppose when you will get response from the server as XML document then inside Ajax code we need to process the XML which is explained below

if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    xmlDoc = xmlhttp.responseXML;
    pname = "";
    pNode = xmlDoc.getElementsByTagName("Person");

    for (i=0;i<pNode.length;i++) {
      pname = pname + pNode[i].childNodes[0].nodeValue;
      pname = pname + "<br />";
    }

    document.getElementById("dataDiv").innerHTML = pname;
}

We need to write above code to parse the data coming from the xml file. Below is the XML file which is coming from server as XML response.-

<List>
   <Lecturer>
      <Title>Mr</Title>
      <Person>Raj Kapoor</Person>
      <Country>USA</Country>
   </Lecturer>
   <Lecturer>
      <Title>Mrs</Title>
      <Person>Sanjana Rai</Person>
      <Country>UK</Country>
   </Lecturer>
</List>

Explanation of Code :

pNode = xmlDoc.getElementsByTagName("Person");

above code will select all tags from the XML document having tag name as ‘Person‘. We need to iterate all the tags from the XML document using for loop.