JavaScript Ajax Tutorial

Introduction to Ajax

Ajax (Asynchronous JavaScript and XML) is a technique for making asynchronous HTTP requests from the browser. It allows you to update parts of a web page without refreshing the entire page.


Using XMLHttpRequest

The XMLHttpRequest object is a core component of making Ajax requests in JavaScript.

Try yourself
        
            
// Using XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);

xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 400) {
        // Request was successful
        const data = JSON.parse(xhr.responseText);
        console.log(data);
    } else {
        // Error occurred
        console.error('Error:', xhr.statusText);
    }
};

xhr.onerror = function() {
    console.error('Error:', xhr.statusText);
};

xhr.send();

        
    

Making GET Requests

You can use Ajax to make GET requests to retrieve data from a server.

Try yourself
        
            
// Making a GET request using Fetch API
fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

        
    

Making POST Requests

POST requests are used to send data to a server, often used for form submissions or sending JSON data.

Try yourself
        
            
// Making a POST request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        userId: 1,
        title: 'New Post',
        body: 'This is the body of the new post.'
    })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

        
    

Using Fetch API

The Fetch API is a modern replacement for XMLHttpRequest, providing a simpler, more powerful way to make HTTP requests.

Try yourself
        
            
// Using the Fetch API
fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('Error:', error);
    });

        
    

Handling Responses

Once a request is made, you'll need to handle the response from the server.

Try yourself
        
            
// Handling a response from a server
fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

        
    

HTTP Methods

Ajax supports various HTTP methods for different types of requests. These include GET, POST, PUT, DELETE, and more.

Try yourself
        
            
// Making a PUT request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts/1', {
    method: 'PUT',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        id: 1,
        title: 'Updated Post Title',
        body: 'Updated body content.'
    })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

// Making a DELETE request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts/1', {
    method: 'DELETE'
})
.then(response => {
    if (!response.ok) {
        throw new Error('Network response was not ok');
    }
    return response.json();
})
.then(data => console.log('Deleted:', data))
.catch(error => console.error('Error:', error));

        
    

Setting Headers

Headers provide additional information about the request or response. You can set custom headers when making Ajax requests.

Try yourself
        
            
// Setting custom headers in a Fetch API request
fetch('https://jsonplaceholder.typicode.com/todos/1', {
    headers: {
        'Custom-Header': 'MyCustomValue'
    }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

        
    

Summary

Ajax is a crucial technique for creating dynamic, interactive web applications. With JavaScript, you can make asynchronous requests to servers, fetch data, and update your web page dynamically. Understanding how to use XMLHttpRequest and the Fetch API, along with handling responses, HTTP methods, and headers, will greatly enhance your web development capabilities.