articles

home / developersection / articles / explain the ajax request in javascript.

Explain the AJAX Request in javascript.

Explain the AJAX Request in javascript.

Ashutosh Kumar Verma 2644 19-Mar-2025

An AJAX request is an asynchronous HTTP request sent from the browser to the server using JavaScript, allowing the exchange of data without refreshing the webpage.

 

Key Components of an AJAX Request

JavaScript (handles the request)

XMLHttpRequest (XHR) or Fetch API (sends/receives data)

Server (processes the request)

Response (JSON, XML, text, HTML) (sent back to the browser)

 

Creating an AJAX Request with XMLHttpRequest (Old Approach)

function loadData() {
   let xhr = new XMLHttpRequest(); // Create an XHR object
   xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true); // Open a GET request
   xhr.onreadystatechange = function () {
       if (xhr.readyState === 4 && xhr.status === 200) { // Ensure request is successful
           console.log(xhr.responseText); // Log response data
       }
   };
   xhr.send(); // Send the request
}

Explain:

  • open(method, url, async): Initiates the request (GET, URL, async true).
  • onreadystatechange: Monitors request state changes.
  • send(): Sends the request to the server.
  • readyState == 4: The request has been completed.
  • status == 200: The HTTP status code for success.

 

Disadvantages of XMLHttpRequest

More complex syntax. 
Requires callbacks to handle responses.

 

AJAX Request Using fetch() (New Approach)

function fetchData() {
   fetch("https://jsonplaceholder.typicode.com/posts/1")
   .then(response => response.json()) // Convert response to JSON
   .then(data => console.log(data)) // Log response data
   .catch(error => console.error("Error:", error)); // Handle errors
}

Advantages of fetch():

  • Simple and clean syntax.
  • Uses Promises for asynchronous handling.
  • More modern and widely adopted.

 

AJAX Request with async/await (Best Practice)

async function fetchDataAsync() {
   try {
       let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
       let data = await response.json();
       console.log(data); // Log response data
   } catch (error) {
       console.error("Error:", error); // Handle errors
   }
}

 

Why use async/await?

  • Easier to read and write
  • Avoid nested callbacks (callback hell)
  • Better error handling using try...catch

 

Sending Data with POST Method

Example-

<!DOCTYPE html>
<html lang="en">
<head>
   <title>JavaScript AJAX Request</title>
</head>
<body>
   <button id="fetchDate">Fetch Data</button>
<div id="output"></div>
<script>
 document.getElementById("fetchDate").addEventListener("click", function(){
  fetch("https://jsonplaceholder.typicode.com/posts", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title: "New Post", body: "This is a test post", userId: 1 })
  })
  .then(response => response.json())
  .then(data => {
   document.getElementById("output").innerHTML = `<h4>${data.title}</h4><p>${data.body}</p>`
   //console.log(data);
  })
  .catch(error => console.error("Error:", error));
 });
</script>
</body>
</html>

 

AJAX Request Lifecycle

sequenceDiagram
   User -> Browser: Clicks Button
   Browser -> Server: Sends AJAX Request
   Server -> Browser: Sends Response (JSON/XML)
   Browser -> User: Updates Web Page Without Reloading

 

I hope you understand clearly about JavaScript AJAX request.

Thanks

 

Also, read: What is Asynchronous JavaScript and XML (AJAX)?

 


I'm a passionate content writer with a deep background in technology and web development. Skilled at writing engaging, well-researched, and SEO-friendly articles, I enjoy simplifying complex topics into clear and impactful writing that informs, inspires, and engages readers.

Leave Comment

Comments

Liked By