AJAX and XMLHttpRequest object

In traditional JavaScript coding, if we want to get any information from a database or a file on the server, or send user information to a server, we will have to make an HTML form and GET or POST data to the server. The user will have to click the “Submit” button to send/get the information, wait for the server to respond, and then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.

With AJAX, our JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object. With an XMLHttpRequest object, a web page can make a request to, and get a response from a web server – without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

Google Suggest (launched in 2005 by Google) is using the XMLHttpRequest object to create a very dynamic web interface: when we start typing in Google’s search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions. The XMLHttpRequest object is supported in all leading web browsers.

Using XMLHttpRequest object we can:
  • Update a web page without reloading it
  • Request data from a web server after the page has been loaded
  • Receive data from a web server  after the page has been loaded
  • Send data to a web server in the background


Create an XMLHttpRequest Object

All major web browsers (Firefox, Chrome, IE7+, Safari, Opera) have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

Old versions of Internet Explorer (IE5 and IE6) use an ActiveX object instead of the XMLHttpRequest object.

So, for handling IE5 and IE6, we have to check if the browser supports the XMLHttpRequest object, or else create an ActiveX object:

variable = new ActiveXObject("Microsoft.XMLHTTP");