Ajax: XMLHttpRequest Object

0
31

XMLHttpRequest Object

What is XMLRequest Object?

The data is exchanged with the server using an XMLHttpRequest object. Using this it is possible to update parts of a web page, without reloading the page.
All modern browsers support XMLHttpRequest object. Older browsers like IE5 and IE6 use ActiveXObject.

Creation of XMLHttpRequest object

The if – else condition is used to check if the browser supports the XMLHttpRequest object. If it does then an XMLHttpRequest object is created. If it is not supported then an ActiveXObject is created.

What does a XMLHttpRequest object do?

An object of XMLHttpRequest is used for asynchronous communication between client and server.

It performs following operations:

  1. Sends data from the client in the background
  2. Receives the data from the server
  3. Updates the webpage without reloading it.

Synchronous vs Asynchronous

A synchronous request blocks the client until operation completes i.e. browser is not unresponsive. In such case, javascript engine of the browser is blocked. When the full page is refreshed at request time and the user is blocked till the request completes.

An asynchronous request doesn’t block the client i.e. browser is responsive. At that time, user can perform another operations also. In such case, javascript engine of the browser is not blocked. Full page is not refreshed at request time and user gets response from the ajax engine.

Properties and Methods of XMLHttpRequest Object

The common properties of XMLHttpRequest object are as follows:

Propery Description
onReadyStateChange It is called whenever readystate attribute changes. It must not be used with synchronous requests.
readyState Represents the state of the request. It ranges from 0 to 4.

  • 0 UNOPENED open() is not called.
  • 1 OPENED open is called but send() is not called.
  • 2 HEADERS_RECEIVED send() is called, and headers and status are available.
  • 3 LOADING Downloading data; responseText holds the data.
  • 4 DONE The operation is completed fully.
reponseText returns response as text.
responseXML returns response as XML

Common Methods of a XMLHttpRequest object

Method Description
void open(method, URL) opens the request specifying get or post method and url.
void open(method, URL, async) same as above but specifies asynchronous or not.
void open(method, URL, async, username, password) same as above but specifies username and password.
void send() sends get request.
void send(string) send post request.
setRequestHeader(header,value) it adds request headers.

Sending a request to the server and receiving a response

A simple GET Request

The above code sample has two statements. The first statement opened a GET Request to the URL ‘ajax.php’ and specifies that it is an asynchronous request.
The second statement sends the GET Request to the Server.

A GET request along with some parameters

The above code opens an asynchronous GET Request to the URL ‘ajax.php’. Also it sends a GET parameter ‘id’ with the request.

A simple POST Request

The above code sends an asynchronous POST request to the URL ‘ajax.php’.

A POST Request with HTTP Header

Asynchronous Request
Sending asynchronous requests is a huge improvement for web developers. Many of the tasks performed on the server are very time consuming. Before AJAX, this operation could cause the application to hang or stop.

With AJAX, the JavaScript does not have to wait for the server response, but can instead:

  • execute other scripts while waiting for server response
  • deal with the response when the response ready

Example Asynchronous Request:

readyState, xmlhttp.status and xmlhttp.responseText will be covered later in the tutorial.

Example Synchronous Request

Synchronous requests are not recommended because the application may hang if the server is busy or is not able to complete the request.

Note: readyState, xmlhttp.status and xmlhttp.responseText are not included while sending a synchronous request.

Server Response

When the request is completed the contents of the div with id “myDiv” are changed with the response coming from the server.

onreadystatechange event

When a request to a server is sent, we want to perform some actions based on the response. The onreadystatechange event is triggered every time the readyState changes. The readyState property holds the status of the XMLHttpRequest.

When readyState is 4 and status is 200, the response is ready.

 

Example – Retrieve data from a text file

With this knowledge, you are ready to make a simple application using AJAX. This demo will guide you how you can create a simple AJAX application.

We are going to retrieve data from a text file.

Make a text file using notepad and put the following content in it:

This is my first AJAX application.

I am so thankful to this tutorial!

Save the file with the name “sample.txt”.

Now make a php file named “index.php” in the same folder as ‘sample.txt’ and put the following code in it.

Explanation

  1. When the button is clicked, loadXML() function is called.
  2. A variable named ‘xmlhttp’ is created.
  3. If the browser supports XMLHttpRequest object (modern browsers like Chrome, IE7+, Firefox, Safari), it is created. If it does not then an ActiveXObject is created.
  4. The onreadystatechange() function is triggered when the readyState changes.
  5. When readyState equals to 4 (meaning DONE) and xmlhttp.status is equal to 200 (meaning OK), the contents of the div “header” are replaced by the response text recieved from the server.
  6. The response text consists of the contents stored in the file “sample.txt”.

 

Example Loading XML file using AJAX

Create an XML file with the name “example.xml”.

Create a PHP file with the following content:

Explanation

  1. When the button is clicked, loadXMLDoc() function is called.
  2. A variable named ‘xmlhttp’ is created.
  3. If the browser supports XMLHttpRequest object (modern browsers like Chrome, IE7+, Firefox, Safari), it is created. If it does not then an ActiveXObject is created.
  4. The onreadystatechange() function is triggered when the readyState changes.
  5. When readyState equals to 4 (meaning DONE) and xmlhttp.status is equal to 200 (meaning OK), the contents of the div “header” are replaced by the response text recieved from the server.
  6. The response text consists of the contents stored in the file “example.xml”.

 

Example – Suggestion Search

This is a suggestion search example. The application will search for the input given by the user in the textbox. The matching input will be displayed on the screen.
Database

Our application consists of an sql database. A Table users is stored in the database consisting of names of some people.

Create a php file named “index.php” with the following code:

Create a php file named “suggest.php” with the following code:

Explanation

  1. Whenever a key is pressed, the function “suggest()” is called.
  2. A XMLHttpRequest object is created depending on the browser compatibility.
  3. A GET request is made to the url “suggest.php”. Note that a GET parameter is also sent while making the request. The parameter is the key pressed from the keyboard.
  4. The GET request is put in a PHP variable. “explode” function breaks the string in the variable. For example, if ‘ABC XYZ’ is passed, then it is broken into ‘ABC’ and ‘XYZ’.
  5. The database query searches in the database for names like the word sent in the request.
  6. The response is then sent back which is displayed in the div “suggestions”.

 

Example – Advanced AJAX-JSON with AJAX

Developers use JSON to pass AJAX updates between client and server. Live scoring websites can be considered as an example of AJAX. The scores are updated automatically as and when they are updated on the server. This enables the webpage to retrieve the score when it is required. This is where we can make use of JSON formatted data.

The below code shows JSON with Ajax, save it in “ajax.php” file. Here loading function loadJSON() will be used asynchronously to upload JSON data.

Following is the input file “data.json” having data in JSON format which will be uploaded asynchronously when we click Update Detail button.

{“name”: “United Kingdom”, “capital”: “London”}

Summary

  • Ajax is a type of programming language made popular in 2005 by Google and other big web developers. Ajax stands for Asynchronous Javascript And XML.
  • AJAX lets the Javascript to communicate directly with the server, using a special Javascript object XMLHttpRequest.
  • Ajax is not a single technology, but a group of technologies.
  • With AJAX it is possible to get information from the server without having to refresh the page!
  • AJAX is popularly used in Google Suggest. Also, chat applications cannot be developed without the use of AJAX.
  • The data is exchanged with the server using an XMLHttpRequest object. Using this it is possible to update parts of a web page, without reloading the page.
  • Ajax is a type of programming language made popular in 2005 by Google and other big web developers. Ajax stands for Asynchronous Javascript And XML.
  • AJAX lets the Javascript to communicate directly with the server, using a special Javascript object XMLHttpRequest.
  • Ajax is not a single technology, but a group of technologies.
  • With AJAX it is possible to get information from the server without having to refresh the page!
  • AJAX is popularly used in Google Suggest. Also, chat applications cannot be developed without the use of AJAX.
  • The data is exchanged with the server using an XMLHttpRequest object. Using this it is possible to update parts of a web page, without reloading the page.

Leave a Reply