Tuesday, October 29, 2024

JavaScript AJAX, XMLHttpRequest and fetch APIs

AJAX is a technique used to make asynchronous HTTP requests from the browser to a server, allowing web pages to retrieve or send data without requiring a full page reload.

AJAX itself is not an API. Instead, AJAX typically involves using either:
  • The XMLHttpRequest (XHR) API: The original API used for AJAX requests.
  • The fetch API: A modern, promise-based API that simplifies making AJAX requests.
How AJAX Works with APIs
While AJAX isn’t an API, it can be used to call various types of APIs, such as RESTful APIs, to retrieve data (like JSON or XML) from a server. This data can be any type of resource — user information, product details, news articles, etc. — provided by the API, and AJAX allows this data to be fetched dynamically.

For example, if you’re calling a REST API to retrieve weather data, you would use AJAX (via XMLHttpRequest or fetch) to make the HTTP request. The server would respond with weather data, which could then be processed and displayed on the webpage without reloading it.

AJAX (Asynchronous JavaScript and XML) allows a web page to fetch data asynchronously without refreshing the page. This is commonly used for updating parts of a webpage in response to user actions, like loading new content or submitting data to the server without a full page reload.

Here's the basic usage of AJAX in vanilla JavaScript using the XMLHttpRequest object:
  1. Create an XMLHttpRequest object
  2. Define a callback function that will handle the server's response
  3. Open the connection to the server
  4. Send the request

// Step 1: Create an XMLHttpRequest object
let xhr = new XMLHttpRequest();

// Step 2: Define a callback function to handle the response
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        // Step 5: Process the response here
        console.log(xhr.responseText); // Prints the response data
    }
};

// Step 3: Open a connection to the server
xhr.open("GET", "https://api.example.com/data", true);

// Step 4: Send the request
xhr.send();

Explanation of the Code
  1. new XMLHttpRequest(): Creates an instance of the XMLHttpRequest object.
  2. xhr.onreadystatechange: Sets a callback function that triggers each time the state of the xhr object changes.
  3. xhr.readyState === 4: Indicates the request is complete.
  4. xhr.status === 200: Checks if the server responded with a status of 200 (OK).
  5. xhr.open("GET", "URL", true): Prepares the request. The first parameter is the HTTP method (GET or POST), the second is the URL, and the third is a boolean indicating whether the request should be asynchronous.
  6. xhr.send(): Sends the request to the server.

AJAX Example with JSON Data
In modern usage, JSON is often used instead of XML for data transfer. Here’s an example of a GET request expecting JSON:
let xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        let data = JSON.parse(xhr.responseText);
        console.log(data); // Output the parsed JSON data
    }
};

xhr.open("GET", "https://api.example.com/data", true);
xhr.send();
AJAX with POST Method
To send data to the server, you use the POST method and set the Content-Type header:

let xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText);
    }
};

xhr.open("POST", "https://api.example.com/data", true);
xhr.setRequestHeader("Content-Type", "application/json");

// Send JSON data
let data = JSON.stringify({ name: "John", age: 30 });
xhr.send(data);

Modern Alternative: Fetch API
The fetch API, which is simpler and more readable, has largely replaced XMLHttpRequest:

fetch("https://api.example.com/data")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error("Error:", error));
This example uses promises, which handle asynchronous operations more naturally than XMLHttpRequest.

No comments:

Post a Comment

Hot Topics