JS Ajax

What is Ajax?

Ajax stands for Asynchronous JavaScript And XML. Ajax allows web pages to dynamically load data from a server and update specific parts of the page without needing to refresh the entire page.

Essentially, Ajax utilizes the browser's built-in XMLHttpRequest (XHR) object to send and receive data from a web server asynchronously. This means it can perform these operations in the background without disrupting the user's interaction with the page.

Ajax has become widely adopted, with many popular web applications relying on it. Examples include Gmail, Google Maps, Google Docs, YouTube, Facebook, Flickr, and numerous others.

Note: Ajax is not a recent technology; in fact, Ajax isn't a distinct technology itself. It's a term used to describe the method of asynchronously exchanging data with a web server using JavaScript, without the need to reload the entire page.

 

Tip: Don't be misled by the term X (from XML) in Ajax. It's primarily a historical artifact. Instead of XML, other data formats like JSON, HTML, or plain text can also be used.

Understanding How Ajax Works

To facilitate Ajax communication, JavaScript utilizes a specialized object embedded within the browser—the XMLHttpRequest (XHR) object—to initiate HTTP requests to the server and handle the response data.

All modern web browsers (Chrome, Firefox, IE7+, Safari, Opera) support the XMLHttpRequest object.

The following diagrams illustrate the process of Ajax communication:

Ajax Illustration

Since Ajax requests are typically asynchronous, the script continues executing as soon as the request is sent. In other words, the browser does not pause script execution while waiting for the server response.

In the next section, we'll explore each step of this process in detail:

Sending Request and Retrieving the Response

Before initiating Ajax communication between the client and server, the first step is to create an instance of the XMLHttpRequest object:

var request = new XMLHttpRequest();

The next step involves configuring the request by using the open() method of the XMLHttpRequest object.

The open() method typically requires two parameters: the HTTP request method, such as "GET", "POST", etc., and the URL to which the request should be sent, like this:

request.open("GET", "info.txt"); -Or- request.open("POST", "add-user");

Tip: The file can be of various types, such as .txt or .xml, or server-side scripting files like .php or .asp. These files can execute server-side actions, such as inserting or retrieving data from a database, before sending a response back to the client.

Lastly, 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 optional body parameter, which allows us to specify the request's body. This is mainly used for HTTP POST requests, as HTTP GET requests do not have a request body, only request headers.

The GET method is commonly used to send a small amount of data to the server. Conversely, the POST method is utilized for sending larger amounts of data, such as form data.

With the GET method, data is sent as URL parameters, visible directly in the URL. In contrast, the POST method sends data within the HTTP request body, keeping it hidden from the URL.

Refer to the chapter on HTTP GET vs. POST for a detailed comparison of these two methods.

Next, we will delve deeper into how Ajax requests function.

Performing an Ajax GET Request

The GET request is typically used to retrieve information from the server without making any changes to the database. For example, fetching search results based on a term or retrieving user details by their ID or name.

The following example demonstrates how to make an Ajax GET request in JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Ajax GET Demo</title>
<script>
function displayFullName() {
// Creating the XMLHttpRequest object
var request = new XMLHttpRequest();

// Instantiating the request object
request.open("GET", "greet.php?fname=John&lname=Clark");

// 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("result").innerHTML = this.responseText;
}
};

// Sending the request to the server
request.send();
}
</script>
</head>
<body>
<div id="result">
<p>Content of the result DIV box will be replaced by the server response</p>
</div>
<button type="button" onclick="displayFullName()">Display Full Name</button>
</body>
</html>

When the request is asynchronous, the send() method returns immediately after sending the request. Therefore, you need to check the current state of the response before processing it. This can be done using the readyState property of the XMLHttpRequest object.

The readyState property is an integer that indicates the status of an HTTP request. Additionally, a 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: The readystatechange event theoretically should be triggered every time the readyState property changes. However, in practice, most browsers do not fire this event when readyState changes to 0 or 1. Nevertheless, all browsers do fire this event when readyState changes to 4.

The status property retrieves the numerical HTTP status code from the XMLHttpRequest's response. Below are some common HTTP status codes:

  • 200 — OK. The server successfully processed the request.
  • 404 — Not Found. The server couldn't locate the requested page.
  • 503 — Service Unavailable. The server is currently unable to handle the request.

For a comprehensive list of response codes, please refer to the HTTP status codes reference.

Here's the code snippet from our "greet" file. It simply concatenates a person's first name and last name to display a greeting message.

Example

Download
<?php
if(isset($_GET["fname"]) && isset($_GET["lname"])) {
$fname = htmlspecialchars($_GET["fname"]);
$lname = htmlspecialchars($_GET["lname"]);

// Creating full name by joining first and last name
$fullname = $fname . " " . $lname;

// Displaying a welcome message
echo "Hello, $fullname! Welcome to our website.";
} else {
echo "Hi there! Welcome to our website.";
}
?>

Performing an Ajax POST Request

The POST method is primarily used for sending form data to a web server.

Here's an example demonstrating how to send form data to the server using Ajax.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Ajax POST Demo</title>
<script>
function postComment() {
// Creating the XMLHttpRequest object
var request = new XMLHttpRequest();

// Instantiating the request object
request.open("POST", "confirmation");

// 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("result").innerHTML = this.responseText;
}
};

// Retrieving the form data
var myForm = document.getElementById("myForm");
var formData = new FormData(myForm);

// Sending the request to the server
request.send(formData);
}
</script>
</head>
<body>
<form id="myForm">
<label>Name:</label>
<div><input type="text" name="name"></div>
<br>
<label>Comment:</label>
<div><textarea name="comment"></textarea></div>
<p><button type="button" onclick="postComment()">Post Comment</button></p>
</form>    
<div id="result">
<p>Content of the result DIV box will be replaced by the server response</p>
</div>    
</body>
</html>

If you're not using the FormData object to send form data, and instead sending the data in query string format like request.send(key1=value1&key2=value2), you'll need to explicitly set the request header using the setRequestHeader() method, as shown below:

request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

The setRequestHeader() method should be called after open() and before send().

Some common request headers include: application/x-www-form-urlencoded, multipart/form-data, application/json, application/xml, text/plain, text/html, and others.

Note: The FormData object simplifies the process of constructing key/value pairs representing form fields and their values, which can be sent using the XMLHttpRequest.send() method. The data transmitted follows the same format that the form's submit() method would use if the form's encoding type were set to multipart/form-data.

Below is the code from our "confirmation" file, which straightforwardly displays the values submitted by the user.

Example

Download
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars(trim($_POST["name"]));
$comment = htmlspecialchars(trim($_POST["comment"]));

// Check if form fields values are empty
if(!empty($name) && !empty($comment)) {
echo "<p>Hi, <b>$name</b>. Your comment has been received successfully.<p>";
echo "<p>Here's the comment that you've entered: <b>$comment</b></p>";
} else {
echo "<p>Please fill all the fields in the form!</p>";
}
} else {
echo "<p>Something went wrong. Please try again.</p>";
}
?>

For security reasons, web browsers restrict Ajax requests to URLs within the same domain as the originating page. This policy, known as the same origin policy, prevents Ajax requests from being made to domains other than the one hosting the original page. However, resources like images, stylesheets, and JavaScript files can still be loaded from any domain.

Tip: Explore the jQuery Ajax methods for easy and efficient implementation of Ajax functionality. jQuery offers convenient methods to simplify the process of integrating Ajax into your web applications.