1. javascript
  2. /async
  3. /ajax

AJAX (Asynchronous JavaScript And XML)

Introduction

AJAX, or Asynchronous JavaScript and XML, is a technique used to create dynamic and interactive web applications. Usually, it's mistaken as a technology, when in fact it's a method of using several different technologies together.

What is AJAX?

AJAX as a technique, allows a web page to update itself without requiring a full page reload. Furthermore, this is achieved by requesting the server for new data and then updating the page with that data without refreshing it.

AJAX can be used to create a wide range of dynamic web applications, such as auto-suggest search boxes, infinite scrolling, and real-time chat applications.

The Technology Bundle Used with AJAX

AJAX relies on several different technologies to work, including:

  • HTML/XHTML and CSS: used to create the structure and layout of the web page.

  • DOM (Document Object Model): used to access and manipulate the elements of the web page.

  • XML or JSON: used to transfer data between the server and the client.

  • XMLHttpRequest: This JavaScript object is used to make requests to the server and receive responses.

  • JavaScript: used to handle the requests and update the page with the new data.

Handling Requests with AJAX

AJAX requests are made using the XMLHttpRequest object, which is built into most modern web browsers. The basic flow of an AJAX request is as follows:

  1. Create a new XMLHttpRequest object

  2. Open a connection to the server

  3. Send the request

  4. Handle the response

Here's an example of a simple AJAX request:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/data', true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText);
    }
};
xhr.send();

We create a new XMLHttpRequest object, and open a connection to the server using the 'GET' method and the URL '/data'. Then, we set the "onreadystatechange" event to handle the response. Once the request is sent, the server will respond with the requested data, which we can then use to update the page.

Using JSON in AJAX

JSON (JavaScript Object Notation) is a lightweight data format that is often used in AJAX applications. In modern-day applications, JSON is usually preferred over XML and can be easily converted to and from JavaScript objects. Here is an example of a JSON response from the server:

Here's an example of a JSON format as a response from the server:

{
    "name": "John Doe",
    "age": 30,
    "email": "[email protected]"
}

To parse a JSON response, we can use the JSON.parse() method. Let's take a look at how to parse a JSON response and update the page with the data:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/data', true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var data = JSON.parse(xhr.responseText);
        document.getElementById("name").innerHTML = data.name;
        document.getElementById("age").innerHTML = data.age;
        document.getElementById("email").innerHTML = data.email;
    }
};
xhr.send();

In the example above, we use the JSON.parse() method to convert the JSON response to a JavaScript object, and then we update the HTML elements on the page with the corresponding data from the object.

Alternatives to XMLHttpRequest

In recent years, new APIs were introduced to replace the XMLHttpRequest object. The most popular of them is the Fetch API, which provides a simpler, more modern way to make network requests.

The Fetch API uses promises to handle requests and responses and can be used in place of the XMLHttpRequest in most cases.

Observe the following example of how to make a request using the Fetch API:

fetch('/data')
    .then(response => response.json())
    .then(data => {
        console.log(data);
    });

Here, we use the fetch() method to make a request to the server, and then use the then() method to handle the response. The response.json() method is used to parse the JSON response, and the data is passed to a callback function where it can be used to update the page.

Using AJAX with Frameworks and Libraries

AJAX is often used in conjunction with various JavaScript frameworks and libraries, such as jQuery and AngularJS. These frameworks and libraries provide a set of abstractions and helper methods that make it easier to work with AJAX and other web technologies.

A basic example of making an AJAX request using jQuery:

$.get('/data', function(data) {
    console.log(data);
});

In this example, we use the jQuery $.get() method to make a request to the server and pass a callback function to handle the response.

AJAX is also commonly used with AngularJS to handle client-side routing and dynamic data binding. Here's an example of how to make an AJAX request using AngularJS:

$http.get('/data').then(function(response) {
    $scope.data = response.data;
});

We use the AngularJS $http service to make a GET request to the server and assign the response data to the $scope object, which can then be used to update the view.

Conclusion

Overall, AJAX is a valuable technique that utilizes different technologies and helps solve the bottlenecks created by modern web application needs. By understanding it, developers can create powerful and engaging web applications that provide a seamless user experience.

To summarise:

  • AJAX is not a technology, but a method of using several different technologies together.

  • The technologies used with AJAX include HTML/XHTML, CSS, DOM, XML, JSON, and JavaScript.

  • Requests are handled using the XMLHttpRequest object or the Fetch API

  • JSON is a common option for data transfer in AJAX applications

  • AJAX can be used with various frameworks and libraries to make development easier.