JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript AJAX Request


An AJAX request is the process of sending a message to a web server and receiving a response without reloading the page. It allows websites to fetch or send data in the background, making the user experience smooth and interactive.

AJAX requests can be made using XMLHttpRequest or the modern Fetch API, but understanding the request process is key to building dynamic web applications.

What Is an AJAX Request?

An AJAX request consists of three main parts:

  1. Request initiation – The client (browser) tells the server it wants data.

  2. Server processing – The server processes the request and prepares a response.

  3. Response handling – The client receives the data and updates the page dynamically.

Requests can be GET or POST, and they can send or receive text, JSON, HTML, or XML data.

Creating a Simple AJAX Request

The XMLHttpRequest object is used to create AJAX requests.

// Create a new XMLHttpRequest object
let xhr = new XMLHttpRequest();

// Define the function to handle the server response
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText); // Log the response text
  }
};

// Initialize a GET request
xhr.open("GET", "data.txt", true);

// Send the request to the server
xhr.send();

Explanation

  • xhr.open("GET", "data.txt", true) prepares a GET request to data.txt.

  • true makes it asynchronous so the page doesn’t freeze.

  • xhr.send() sends the request.

  • xhr.onreadystatechange runs whenever the readyState changes.

  • When readyState is 4 and status is 200, the response is ready and successful.

GET vs POST Requests

GET Request: Retrieves data from the server. Parameters are sent in the URL.

xhr.open("GET", "server.php?user=Vicky", true);
xhr.send();

POST Request: Sends data to the server. Parameters are sent in the request body.

xhr.open("POST", "server.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("user=Vicky&age=28");

Key Differences:

  • GET is visible in the URL; POST is hidden in the request body.

  • POST can send larger amounts of data.

  • GET is generally faster and can be cached; POST is used for sensitive or large data.

Handling Responses

AJAX responses can be of different types:

  • Text: Plain text content from a server.

  • HTML: A snippet of HTML code to be inserted into a page.

  • JSON: Structured data used in modern web applications.

Example: Handling JSON Response

let xhr = new XMLHttpRequest();
xhr.open("GET", "user.json", true);

xhr.onload = function() {
  if (xhr.status === 200) {
    let user = JSON.parse(xhr.responseText); // Convert JSON to JS object
    console.log("User Name:", user.name);
    console.log("User Age:", user.age);
  }
};

xhr.send();

Here, JSON.parse() converts the JSON string from the server into a JavaScript object.

Setting Request Headers

Headers provide additional information to the server. For example, when sending JSON data:

let xhr = new XMLHttpRequest();
xhr.open("POST", "server.php", true);
xhr.setRequestHeader("Content-Type", "application/json");

let data = { name: "Vicky", age: 28 };
xhr.send(JSON.stringify(data));

Explanation:

  • setRequestHeader() specifies that the request body is JSON.

  • JSON.stringify(data) converts a JavaScript object to a JSON string for sending.

Handling Errors

It is important to handle errors properly in AJAX requests.

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      console.log("Request Successful:", xhr.responseText);
    } else if (xhr.status === 404) {
      console.error("Error 404: File not found");
    } else {
      console.error("Error:", xhr.status);
    }
  }
};

This ensures your web application can react gracefully if something goes wrong.

Example: Displaying Server Response in a Page

<button id="loadBtn">Load Data</button>
<div id="result"></div>

<script>
document.getElementById("loadBtn").addEventListener("click", function() {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "data.txt", true);

  xhr.onload = function() {
    if (xhr.status === 200) {
      document.getElementById("result").textContent = xhr.responseText;
    } else {
      document.getElementById("result").textContent = "Failed to load data";
    }
  };

  xhr.send();
});
</script>

Explanation:

  • Fetches data from data.txt.

  • Displays it in a <div> with id result.

  • The page doesn’t reload.

Using Options with Requests

AJAX requests can also include options like timeout or credentials.

xhr.timeout = 5000; // Timeout in milliseconds
xhr.ontimeout = function() {
  console.error("Request timed out");
};

xhr.withCredentials = true; // Include cookies if needed

This makes AJAX requests more robust and secure.

Summary of the Tutorial

An AJAX request is the core of modern interactive websites. Using XMLHttpRequest, you can send or fetch data asynchronously, handle JSON, HTML, or text responses, set headers, and manage errors effectively.

Key points:

  • Use GET for fetching data, POST for sending data.

  • Always check readyState and status to handle responses properly.

  • You can send headers and structured data (JSON) for better server communication.

  • AJAX requests improve user experience by eliminating page reloads.

Mastering AJAX requests is essential for building dynamic, responsive, and modern web applications.


Practice Questions

  1. Write an AJAX GET request to fetch data.txt and display its content inside a <div> when a button is clicked.

  2. Create an AJAX POST request to send a username and email to submit.php and display the server response in a <p> element.

  3. Write code to handle different HTTP status codes (200, 404, 500) and display appropriate messages on the page.

  4. Fetch a JSON file (user.json) and display the name and age of the user in separate <span> elements.

  5. Modify an AJAX request to show a “Loading…” message while waiting for the server response and replace it with the actual data once received.

  6. Create two buttons that send AJAX requests to two different files (students.txt and teachers.txt) and display the content in the same <div>.

  7. Use setRequestHeader to send JSON data in a POST request and display the server response.

  8. Write an AJAX request that times out after 5 seconds and shows an alert if the request exceeds this time.

  9. Fetch an HTML snippet (snippet.html) and insert it into a specific <section> of the page without reloading the page.

  10. Write a function that sends multiple AJAX requests sequentially and logs each response in the console.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top