What is AJAX in Javascript and how does it work?

Category
Website
Reading
7 mins
Views
778
Posting
19 Aug 2023

Talking about websites, there are many things that must be understood, one of which is AJAX, this method is widely used in small and large-scale websites that require many requests. AJAX or Asynchronous Javascript And XML is a technique in developing a website when executing a command to the server.

This will allow the interface does not need to refresh the page to display the data, because it works asynchronously or indirectly. AJAX relies heavily on Javascript, because to run this method, the Javascript programming language is needed to manage dynamic content.

 

What is AJAX in Javascript And How its works

 

 

1. What is AJAX in Javascript

AJAX is a method commonly used in website interfaces to interact with servers without requiring page reloading. In terms of performance, it turns out that this technique is quite fast compared to using conventional techniques, where this technique will make the user not have to wait for the page to reload and make the interaction in the front-end more interactive.

Examples of cases that we often encounter is in the Google search field. When we are going to search for something by typing in the search field, several suggested sentences will appear below to show the user what they are looking for, that's a simple example of the AJAX technique.

AJAX will quickly respond to what the user is looking for by communicating with the server without having to refresh a page. This method makes server performance lighter, because the requested request will be given according to the user's wishes. AJAX itself is not a technology, but just a technique in Javascript to dynamically connect to the server.

XMLHTTPRequest is an object that refers to the use of data to interact with the server. Like HTML that displays data into the browser, XMLHTTPRequest aims to bring data into the browser via Javascript. This method uses XHTML for the content in conjunction with the DOM or Document Object Model to manipulate the HTML.

Fundamentally, knowledge of the DOM must be mastered by developers if they want to use this technique, because the data will be displayed via AJAX and will usually be manipulated into HTML to display content dynamically. For example, to fill out a form in HTML, a website that does not use AJAX will send information to the server in synchronization and will be redirected to another page.

While websites that use AJAX, the way it works is not like that, when the user sends data via a button, Javascript will make a request to the server, then process the results and update the display without redirecting to another page.

 

2. Example of techniques in AJAX

This concept actually existed around the 90s, but the old version of AJAX was not as popular as it is today. The concept of AJAX was popularized by Google who applied this technique to their products. This technique is widely used in various things such as notifications, chat, forms, searching, displaying cards asynchronously (load more), asynchronous pagination or product ratings.

A different approach on a web page using AJAX, for example to display a product page using asynchronous. Just imagine if on one page there are thousands of products that are displayed simultaneously into the interface, it will obviously burden the server and database, drain a lot of bandwidth and make users uncomfortable because they have to scroll through website pages endlessly.

By using the asynchronous technique, a product website page can display 6 products for example, then press the load more button to display the next 6 products. From the simple example above, we can conclude that AJAX is indeed very useful from various sides, especially interacting with users. Here is an example of AJAX code on vanilla Javascript and JQuery:

1. Vanilla Javascript

// Vanilla Javascript
var http = new XMLHttpRequest();
http.addEventListener("load", () => {
  console.log(http.responseText);
});
http.open("GET", "https://example.com/api");
http.send();

2. jQuery

// jQuery AJAX
$(document).ready(function () {
    $.ajax({
      async: true,
      type: "GET",
      dataType: "json",
      url: "https://example.com/api",
      success: function (data) {
        console.log(data);
      },
    });
});

 

3. How does AJAX work on websites

Generally, this technique consists of several system components including HTML, DOM, XML, XMLHTTPRequest and Javascript.

  • HTML itself is the main language used to present data into the browser.
  • DOM is a technique for manipulating HTML documents to display data dynamically.
  • XML is used to exchange data, but in today's modern websites, XML is rarely used and has been replaced with JSON (JavaScript Object Notation), because it is easy to use and the process is fast.
  • XMLHTTPRequest serves to communicate with the server indirectly or asynchronously.
  • Javascript is the main language for creating AJAX methods and integrating with other components perfectly.

Actually, if you already understand the basics of Javascript, using this technique is not difficult. Here are some comparisons between the conventional flow of concepts with concepts that use AJAX:

1. Conventional Concept Flow

  • The request will be sent to the browser for processing on the server.
  • The server receives the data and processes it.
  • The server will return the requested data.
  • The web browser will receive the data and then reload the page as a sign that the data has been processed.

2. AJAX Concept Flow

  • The browser will make a call to the server using an XMLHTTPRequest and send it to the server.
  • The server receives the data and then returns the requested data to the browser.
  • The browser receives data from the server and is immediately displayed into the interface without reloading the page as a sign that the data has been processed.

From the two comparisons, it can be concluded that by using this technique, the browser does not need to reload the page to display data into the interface, unlike conventional workflows that require the user to wait for the page to finish reloading when displaying data.

 

4. How to use fetch for AJAX POST requests

You can also use other methods besides vanilla javascript and jQuery AJAX to make requests, namely by using fetch, fetch is a built-in API from the browser to make requests as well as jQuery AJAX in data requests. In terms of code, fetch itself is more modern than xmlhttprequest and easy to use. I recommend you to use fetch to do AJAX because it is easier to understand. Here is an example of code in using fetch:

const url = 'https://api.example.com/data'; // Replace with the appropriate API URL
const data = {
  key1: 'value1',
  key2: 'value2'
}; // Replace with the data you want to send

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json', // Set the content type as needed
    // 'Authorization': 'Bearer token' // If authorization is needed, add token here
  },
  body: JSON.stringify(data) // Convert data object to JSON string
})
.then(response => {
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json(); // Return the response as JSON object
})
.then(data => {
  console.log('Response:', data); // Action to take after getting a successful response
})
.catch(error => {
  console.error('Error:', error); // Handle errors if the request fails
});

The code above is an example of using fetch in requests with the POST method, the data sent is an object that has keys and values, using headers for authorization or determining the type of content sent. In handling, this fetch uses promise, the then block that handles the response from the server after the data request is successfully sent, then it will capture the response from the data if it is successfully processed and return it in json form.

Furthermore, the catch block is used to capture error messages if available, usually this error message will capture error messages such as server errors or bad internet connections and can print them into the console.

 

5. What are the benefits of AJAX on the website

Some of the benefits that website owners feel when they use this technique in their website applications include:

1. Improve website performance

This technique was originally created to improve website performance in terms of speed and functionality. With AJAX, a web page does not need to display the data in the database in full. The server will not work until it receives the request from the browser only. Website users can make data requests according to their needs without having to wait for the page to be completely updated.

2. Improve User Experience (UX)

AJAX can improve a good experience for users, because websites are much faster when they want to make data requests and will reduce unnecessary page reloads and optimize only certain pages. This method can improve browser performance and facilitate interaction with the server, thus providing a better user experience.

3. Reduce unnecessary bandwidth

AJAX can lighten the network load and avoid unnecessary bandwidth usage. That's because this method only processes data and retrieves data efficiently thus providing a responsive speed experience.

4. Supported by various browsers

Almost all current browsers support modern websites that use AJAX techniques, starting from Google Chrome, Microsoft Edge, Mozilla Firefox, Opera and Mobile Browsers.

 

Conclusion

AJAX is a technique in websites to make it easier for users, reduce unnecessary bandwidth and provide a good experience for users. The use of this technique is actually not too difficult to use if you already understand the basics of Javascript and can be implemented according to the needs of your website.

Share