AJAX is a developer's dream, because you can:
The HTML page contains a <div> section and a <button>.
The <div> section is used to display information from a server.
The <button> calls a function (if it is clicked).
The function requests data from a web server and displays it:
AJAX = Asynchronous JavaScript And XML.
AJAX is not a programming language.
AJAX just uses a combination of:
XMLHttpRequest object (to request data from a web
server)AJAX is a misleading name. AJAX applications might use XML to transport data, but it is equally common to transport data as plain text or JSON text.
AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Modern Browsers can use Fetch API instead of the XMLHttpRequest Object.
The Fetch API interface allows web browser to make HTTP requests to web servers.
If you use the XMLHttpRequest Object, Fetch can do the same in a simpler way.
The keystone of AJAX is the XMLHttpRequest object.
All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object can be used to exchange data with a web server
behind the scenes. This means that it is possible to update parts of a web page, without reloading
the whole page.
All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have a
built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
A callback function is a function passed as a parameter to another function.
In this case, the callback function should contain the code to execute when the response is ready.
To send a request to a server, you can use the open() and send() methods of
the XMLHttpRequest object:
For security reasons, modern browsers do not allow access across domains.
This means that both the web page and the XML file it tries to load, must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools domain.
If you want to use the example above on one of your own web pages, the XML files you load must be located on your own server.
| Method | Description |
|---|---|
| new XMLHttpRequest() | Creates a new XMLHttpRequest object |
| abort() | Cancels the current request |
| getAllResponseHeaders() | Returns header information |
| getResponseHeader() | Returns specific header information |
| open(method, url, async, user, psw) | Specifies the request method: the request type GET or POST url: the file location async: true (asynchronous) or false (synchronous) user: optional user name psw: optional password |
| send() | Sends the request to the server Used for GET requests |
| send(string) | Sends the request to the server. Used for POST requests |
| setRequestHeader() | Adds a label/value pair to the header to be sent |
| Property | Description |
|---|---|
| onload | Defines a function to be called when the request is received (loaded) |
| onreadystatechange | Defines a function to be called when the readyState property changes |
| readyState | Holds the status of the XMLHttpRequest. 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready |
| responseText | Returns the response data as a string |
| responseXML | Returns the response data as XML data |
| status | Returns the status-number of a request 200: "OK" 403: "Forbidden" 404: "Not Found" For a complete list go to the Http Messages Reference |
| statusText | Returns the status-text (e.g. "OK" or "Not Found") |
With the XMLHttpRequest object you can define a callback function to be
executed when the request receives an answer.
The function is defined in the onload property of
the XMLHttpRequest object:
If you have more than one AJAX task in a website, you should create one function for executing
the XMLHttpRequest object, and one callback function for each AJAX task.
The function call should contain the URL and what function to call when the response is ready.
The readyState property holds the status of the XMLHttpRequest.
The onreadystatechange property defines a callback function to be executed
when the readyState changes.
The status property and the statusText properties hold
the status of the XMLHttpRequest object.
| Property | Description |
|---|---|
| onreadystatechange | Defines a function to be called when the readyState property changes |
| readyState | Holds the status of the XMLHttpRequest. 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready |
| status | 200: "OK" 403: "Forbidden" 404: "Page not found" For a complete list go to the Http Messages Reference |
| statusText | Returns the status-text (e.g. "OK" or "Not Found") |
The onreadystatechange function is called every time the readyState changes.
When readyState is 4 and status is 200, the response is ready:
The onreadystatechange event is triggered four times (1-4), one time for
each change in the readyState.
The XMLHttpRequest object is used to request data from a server.
To send a request to a server, we use the open() and send() methods of
the XMLHttpRequest object:
| Method | Description |
|---|---|
| open(method, url, async) | Specifies the type of request method: the type of request: GET or POST url: the server (file) location async: true (asynchronous) or false (synchronous) |
| send() | Sends the request to the server (used for GET) |
| send(string) | Sends the request to the server (used for POST) |
The url parameter of the open() method, is an address to a file on a server:
The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php (which can perform actions on the server before sending the response back).
Server requests should be sent asynchronously.
The async parameter of the open() method should be set to true:
By sending asynchronously, the JavaScript does not have to wait for the server response, but can instead:
The default value for the async parameter is async = true.
You can safely remove the third parameter from your code.
Synchronous XMLHttpRequest (async = false) is not recommended because the JavaScript will stop executing until the server response is ready. If the server is busy or slow, the application will hang or stop.
GET is simpler and faster than POST, and can be used in most
cases.
However, always use POST requests when:
A simple GET request:
In the example above, you may get a cached result. To avoid this, add a unique ID to the URL:
If you want to send information with the GET method, add the information to
the URL:
How the server uses the input and how the server responds to a request, is explained in a later chapter.
A simple POST request:
To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify
the data you want to send in the send() method:
| Method | Description |
|---|---|
| setRequestHeader(header, value) | Adds HTTP headers to the request header: specifies the header name value: specifies the header value |
To execute a synchronous request, change the third parameter in
the open() method to false:
Sometimes async = false are used for quick testing. You will also find synchronous requests in older JavaScript code.
Since the code will wait for server completion, there is no need for
an onreadystatechange function:
| Property | Description |
|---|---|
| responseText | get the response data as a string |
| responseXML | get the response data as XML data |
The responseText property returns the server response as a JavaScript string,
and you can use it accordingly:
The XMLHttpRequest object has an in-built XML parser.
The responseXML property returns the server response as an XML DOM object.
Using this property you can parse the response as an XML DOM object:
Request the file cd_catalog.xml and parse the response:
| Method | Description |
|---|---|
| getResponseHeader() | Returns specific header information from the server resource |
| getAllResponseHeaders() | Returns all the header information from the server resource |
The getAllResponseHeaders() method returns all header information from the
server response.
The getResponseHeader() method returns specific header information from the
server response.
AJAX can be used for interactive communication with an XML file.
The following example will demonstrate how a web page can fetch information from an XML file with AJAX:
When a user clicks on the "Get CD info" button above, the loadDoc() function
is executed.
The loadDoc() function creates
an XMLHttpRequest object, adds the function to be executed when the server
response is ready, and sends the request off to the server.
When the server response is ready, an HTML table is built, nodes (elements) are extracted from the XML file, and it finally updates the element "demo" with the HTML table filled with XML data:
The XML file used in the example above looks like this: "cd_catalog.xml".
AJAX is used to create more interactive applications.
The following example demonstrates how a web page can communicate with a web server while a user types characters in an input field:
Start typing a name in the input field below:
Suggestions:
First name:
In the example above, when a user types a character in the input field, a function
called showHint() is executed.
The function is triggered by the onkeyup event.
Here is the code:
Code explanation:
First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint placeholder and exit the function.
However, if the input field is not empty, do the following:
The PHP file checks an array of names, and returns the corresponding name(s) to the browser:
AJAX is used to create more interactive applications.
The following example will demonstrate how a web page can communicate with a web server while a user type characters in an input field:
Start typing a name in the input field below:
Suggestions:
First name:
In the example above, when a user types a character in the input field, a function
called showHint() is executed.
The function is triggered by the onkeyup event.
Here is the code:
Code explanation:
First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint placeholder and exit the function.
However, if the input field is not empty, do the following:
The ASP file checks an array of names, and returns the corresponding name(s) to the browser:
AJAX can be used for interactive communication with a database.
The following example will demonstrate how a web page can fetch information from a database with AJAX:
When a user selects a customer in the dropdown list above, a function
called showCustomer() is executed. The function is triggered by
the onchange event:
The showCustomer() function does the following:
The page on the server called by the JavaScript above is a PHP file called "getcustomer.php".
The source code in "getcustomer.php" runs a query against a database, and returns the result in an HTML table:
This chapter demonstrates some HTML applications using XML, HTTP, DOM, and JavaScript.
In this chapter we will use the XML file called "cd_catalog.xml".
This example loops through each <CD> element, and displays the values of the <ARTIST> and the <TITLE> elements in an HTML table:
For more information about using JavaScript and the XML DOM, go to DOM Intro.
This example uses a function to display the first CD element in an HTML element with id="showCD":
To navigate between the CDs in the example above, create
a next() and previous() function:
The last example shows how you can show album information when the user clicks on a CD: