Question: How can I request data from the server without reloading the page in the browser?

Answer: JavaScript code loaded in the client browser can request additional data from the Web server using the XMLHttpRequest object. Try it now:

In this example, when you click the Send Request button, the browser requests additional data from the server (the file requested_file.htm), and then displays the returned data in a message box, by executing the following JavaScript code:

var oRequest = new XMLHttpRequest();
var sURL = "http://"
         + self.location.hostname
         + "/faq/requested_file.htm";


if (oRequest.status==200) alert(oRequest.responseText);
else alert("Error executing XMLHttpRequest call!");

In most modern browsers, the general syntax of the XMLHttpRequest.open() method is as follows:

var oRequest = new XMLHttpRequest();
oRequest.open( method, URL, async )

The parameters method, URL, async have the following meaning:
method Specifies the method to be used for the HTTP request. Can be one of the following: "GET", "POST", "HEAD".
URL Specifies the URL to which the request will be sent when the XMLHttpRequest.send() method is executed.
async Boolean. If true, specifies that the HTTP request should be performed asynchronously, that is, without forcing the code execution to wait until the request's results are returned to the browser.

Note that the XMLHttpRequest.open() method itself does not send the request to the Web server. It is the XMLHttpRequest.send() method that actually sends the request.

Historical Note. In older browsers, e.g. in Microsoft Internet Explorer 6 or earlier, you might not be able to instantiate the XMLHttpRequest using the above simple syntax: new XMLHttpRequest(). Instead, depending on the actual client configuration, you'd have to use one of the following statements:

oRequest = new ActiveXObject("Msxml2.XMLHTTP");
oRequest = new ActiveXObject("Microsoft.XMLHTTP");

Copyright © 1999-2011, JavaScripter.net.