Introduction
AJAX isn't a new programming language, but a technique for building fast, dynamic pages. With it, you can
- Update content without reloading the page
- Request data from a server
- Download data from a server
- Send data to a server in the background
Definition
AJAX = Asynchronous JavaScript and XML. The name is a bit misleading, because you can use AJAX even if you don't know XML.
Applications
Apps that use AJAX include Google Maps, Gmail, YouTube, Facebook, and more.
How AJAX Works

AJAX Is Based on Internet Standards
AJAX is based on internet standards, mainly these two
- XMLHttpRequest object (to retrieve data from a web server)
- JavaScript/DOM (to display/use the data)
AJAX became popular in 2005 because of Google Suggest. As you type in the search box, JavaScript sends data to the server, and the server returns a list of suggestions based on your input.
XMLHttpRequest object
The XMLHttpRequest object is the foundation of AJAX. All modern browsers support the XMLHttpRequest object, which is used to exchange data with a server.
Create an XMLHttpRequest objectxhr = new XMLHttpRequest();
Sending an AJAX Request
We use the XMLHttpRequest object's open() and send() methods to send a request:
GET
|
|
POST
|
|

Add headers
|
|

The definition makes it clear that AJAX is asynchronous, so the third argument to open() is set to true. Asynchronous execution is great news for developers. Server-side work is usually slow, and before AJAX, many operations could cause the page to hang or stop. With AJAX, JavaScript no longer has to keep waiting for the server's response
- Scripts can keep running while waiting for the server's response
- The response can be handled as soon as it's ready.
|
|
Server Response
Use the XMLHttpRequest object's responseText (as String) and responseXML (as XML) properties to get the server's response.
responseText
responseXML
|
|
The AJAX onreadystatechange Event
If you look closely, we've already used some events, such as onreadystatechange for when the response is ready. After sending a request, we want to take action based on the server's response. The onreadystatechange event fires every time readyState changes. readyState holds the status of the XMLHttpRequest. The
image below shows some important properties of the XMLHttpRequest object
In this image, you can see that the response is ready when readyState is 4 and status is 200. Here's an example in code:
|
|
AJAX and PHP
This example shows how a web page communicates with the server as you type characters. Here's the source code:
|
|
PHP file gethint.php
|
|
##AJAX and Databases
This example shows how a web page uses AJAX to fetch data from a database
|
|
getcustomer.asp queries the database and returns the information to the HTML page
|
|
Reference: w3schools
