XML HttpRequest

To request data from a server, a built-in XMLHttpRequest object is present in all modern browsers.

The XMLHttpRequest Object:

To request data from a web server, the XMLHttpRequest object can be used which is much like a dream for a developer. The reasons are:

  • The XMLHttpRequest object can update a web page without reloading the page.
  • The XMLHttpRequest object can request data from a server – after the page has loaded.
  • The XMLHttpRequest object can receive data from a server – after the page has loaded.
  • The XMLHttpRequest object can send data to a server – in the background.

Sending an XMLHttpRequest:

To use the XMLHttpRequest object, a common JavaScript syntax which looks much like below:

Example:

<!DOCTYPE html>
<html>
<body>
 
<h2>XMLHttpRequest Object</h2>
 
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change</button>
</div>
 
<script>
function loadXMLDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "info.txt", true);
  xhttp.send();
}
</script>
 
</body>
</html>

Output:

Explanation:

  • In the above example, we are creating an XMLHttpRequest object in the first line, i.e. :
    var xhttp = new XMLHttpRequest();
  • To define a function to be executed every time the status of the XMLHttpRequest object changes, the onreadystatechange property is used, i.e. :
    xhttp.onreadystatechange = function()
  • The response will be ready, if the readyState property is 4 and the status property is 200, i.e.:
    if (this.readyState == 4 && this.status == 200)
  • The server response is returned as a text string, by the responseText property. Now, to update a web page, the text string can be used, i.e.
    document.getElementById("demo").innerHTML = xhttp.responseText;

Old Versions of Internet Explorer (IE5 and IE6):

The XMLHttpRequest object is not supported by the old versions of Internet Explorer (IE5 and IE6). We need to first determine if the browser supports the XMLHttpRequest object to handle IE5 and IE6, otherwise, we need to create an ActiveXObject.

Example:

<!DOCTYPE html>
<html>
<body>
 
<h2>XMLHttpRequest Object</h2>
 
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change</button>
</div>
 
<script>
function loadXMLDoc() {
  var xmlhttp;
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  } else {
    // code for older browsers
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xmlhttp.open("GET", "info.txt", true);
  xmlhttp.send();
}
</script>
 
</body>
</html>

Output:

Please Share