The following is a very simple demo to showcase how to query a server resource with XHR. The server resource, in this case, it's just a one-line HTML file - data1.html (you may click there to see how simple the page is)

Anyway, below is how exactly the HTML file looks like, it is not even a proper HTML file.

<h4>I am Data</h4>

When you click on the "Get Data" button, XHR simply fetches the response of data1.html from web server. We then populate the response into div1.

The simple click that you have just done can be broken into 3 steps.

  1. Step 1 Instantiate / Create an XHR instance
  2. Step 2 Define how to handle the response from the server by creating Ready State Handler.
  3. Step 3 Specify your request method (GET or POST), url and send to the server
function GetData() {
    // 1. Instantiate XHR - Start 
var xhr; if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); else if (window.ActiveXObject) xhr = new ActiveXObject("Msxml2.XMLHTTP"); else throw new Error("Ajax is not supported by your browser"); // 1. Instantiate XHR - End // 2. Handle Response from Server - Start xhr.onreadystatechange = function () { if (xhr.readyState < 4) document.getElementById('div1').innerHTML = "Loading..."; else if (xhr.readyState === 4) { if (xhr.status == 200 && xhr.status < 300) document.getElementById('div1').innerHTML = xhr.responseText; } } // 2. Handle Response from Server - End // 3. Specify your action, location and Send to the server - Start'GET', ''); xhr.send(null); // 3. Specify your action, location and Send to the server - End } </script>