AJAX stands for Asynchronous JavaScript And XML. It is not a programming language. It is a technology for developing better, faster, and more interactive Web Applications using HTML, CSS, JavaScript, and XML.
Ajax stands for Asynchronous Javascript And XML. Ajax is just a means of loading data from the server and selectively updating parts of a web page without reloading the whole page.
What Ajax does is make use of the browser's built-in XMLHttpRequest
(XHR) object to send and receive information to and from a web server asynchronously, in the background, without blocking the page or interfering with the user's experience.
Ajax has become so popular that you hardly find an application that doesn't use Ajax to some extent. Examples of some large-scale Ajax-driven online applications are Gmail, Google Maps, Google Docs, YouTube, Facebook, Flickr, and so many others applications.
XML : Extensible Markup Language (XML) is a format to store and transport data from the Web Server.
What's the meaning of Asynchronous in AJAX?
Asynchronous means that the Web Application could send and receive data from the Web Server without refreshing the page. This background process of sending and receiving data from the server and updating different web page sections defines the Asynchronous property/feature of AJAX.
Understanding How Ajax Works?
To perform Ajax communication JavaScript uses a particular object built into the browser—an XMLHttpRequest
(XHR) thing—to make HTTP requests to the server and receive data in response.
All modern browsers (Chrome, Firefox, IE7+, Safari, Opera) support the XMLHttpRequest
object.
The following illustrations demonstrate how Ajax communication works:
Since Ajax requests are usually asynchronous, execution of the script continues as soon as the Ajax request is sent, i.e. the browser will not halt the script execution until the server response comes back.
Sending Request and Retrieving the Response
Before you perform Ajax communication between client and server, the first thing you must do is instantiate an XMLHttpRequest
object, as shown below:
var request = new XMLHttpRequest();
Now, the next step in sending the request to the server is to instantiate the newly-created request object using the open()
method of the XMLHttpRequest object.
The open()
the method typically accepts two parameters— the HTTP request method to use, such as "GET", "POST", etc., and the URL to send the request to, like this:
request.open("GET", "info.txt"); -Or- request.open("POST", "add-user.php");
NOTE: The file can be of any kind, like
.txt
or.xml
, or server-side scripting files, like.php
or.asp
, which can perform some actions on the server (e.g. inserting or reading data from database) before sending the response back to the client.
And finally, send the request to the server using the send()
method of the XMLHttpRequest object.
request.send(); -Or- request.send(body);
NOTE**:** The
send()
method accepts an optionalbody
parameter which allow us to specify the request's body. This is primarily used for HTTP POST requests, since the HTTP GET request doesn't have a request body, just request headers.
Performing an Ajax GET Request
The GET request is typically used to get or retrieve some kind of information from the server that doesn't require any manipulation or change in the database, for example, fetching search results based on a term, fetching user details based on their id or name, and so on.
The following example will show you how to make an Ajax GET request in JavaScript:
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
// Creating the XMLHttpRequest object
var request = new XMLHttpRequest();
// Instantiating the request object
request.open("GET", "https://jsonplaceholder.typicode.com/todos/1");
// Defining event listener for readystatechange event
request.onreadystatechange = function() {
// Check if the request is compete and was successful
if(this.readyState === 4 && this.status === 200) {
// Inserting the response from server into an HTML element
document.getElementById("demo").innerHTML = this.responseText;
}
};
// Sending the request to the server
request.send();
}
</script>
</body>
</html>
OUTPUT:
When the request is asynchronous, the send()
the method returns immediately after sending the request. Therefore you must check where the response currently stands in its lifecycle before processing it using the readyState
property of the XMLHttpRequest
object.
The readyState
is an integer that specifies the status of an HTTP request. Also, the function assigned to the onreadystatechange
event handler is called every time the readyState
property changes. The possible values of the readyState
property are summarized below.
Value | State | Description |
0 | UNSENT | An XMLHttpRequest object has been created, but the open() method hasn't been called yet (i.e. request not initialized). |
1 | OPENED | The open() method has been called (i.e. server connection established). |
2 | HEADERS_RECEIVED | The send() method has been called (i.e. server has received the request). |
3 | LOADING | The server is processing the request. |
4 | DONE | The request has been processed and the response is ready. |
NOTE: Theoretically, the
readystatechange
event should be triggered every time thereadyState
property changes. But, most browsers do not fire this event whenreadyState
changes to 0 or 1. However, all browsers fire this event whenreadyState
changes to 4 .
Performing an Ajax POST Request
The POST method is mainly used to submit form data to the web server.
The following example will show you how to submit form data to the server using Ajax.
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Post data</button>
<script>
function loadDoc() {
// Creating the XMLHttpRequest object
var request = new XMLHttpRequest();
// Instantiating the request object
request.open("POST", "https://jsonplaceholder.typicode.com/posts");
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// Sending the request to the server
request.send(JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}));
}
</script>
</body>
</html>
OUTPUT: