GET, POST, PUT & DELETE using AJAX in JavaScript

Reading Time: 3 minutes 🕑

Last updated: August 21, 2022.

You can use AJAX in JavaScript to send and receive data from servers in frontend JavaScript.

The term AJAX is an acronym for Asynchronous JavaScript And XML.

Though AJAX refers to no particular technology in particular, in vanilla JavaScript it is synonymous with making HTTP requests using the native XMLHttpRequest object.

In this tutorial, you will learn how to make all possible types of request using AJAX:

  • GET: Receive data from a server.
  • POST: Send data to a server.
  • PUT: Send and overwrite existing data (usually an entry).
  • DELETE: Delete data from a server.
Table of contents

Using AJAX

GET request

To make a GET request, call new XMLHttpRequest() to create a new request object.

Configure the request by calling the open() method on the new object. The first argument you pass in specifies the type of request (here GET). The second specifies the URL endpoint for the GET request. In this case, we are using a test endpoint provided by reqres.in, which, in the case of a successful request, will return (fictitious) user data.

Before sending, add an event listener to the request, listening out for a load event. Its associated function will fire when the request and response is complete.

The data you receive is stored in responseText and will be in JSON format. Therefore, it is wrapped in JSON.parse() to convert the response data from JSON to a JavaScript object.

Finally, call send() on the request to execute it.

const req = new XMLHttpRequest();

req.open('GET', 'https://reqres.in/api/users');

req.addEventListener('load', function() {
    const res = JSON.parse(req.responseText);
    console.log(res);
});

req.send();

To add error-handling, add a conditional check on the values of readyState and status on the request object after the load event has occurred.

If the value of readyState is 4 (request complete) and the value of status is 200 (success), you are able to access the payload via responseText on the request object.

If not, you will want to initiate your error-handling response.

const req = new XMLHttpRequest();

req.open('GET', 'https://reqres.in/api/users');

req.addEventListener('load', function() {
    if (req.readyState === 4 && req.status === 200) {
        const res = JSON.parse(req.responseText);
        console.log(res);
    } else {
        console.log("Request error");
    }
});

req.send();

POST or PUT request

To send data with AJAX, set the response type to POST (or PUT) by changing the first argument inside the request object.

Because you are sending a payload, you need to specify to the server what type of data you are sending. Set this to 'application/json' as the JavaScript object we will send in this example will be converted to JSON format.

You place the payload as an argument when calling send() to execute the request.

To convert the JavaScript object to JSON, the payload is wrapped in JSON.stringify() which will do this parsing for us.

const user = {
    name: "Nicholas Cage",
    address: "Oakwood Street",
}

const req = new XMLHttpRequest();

req.open('POST', 'https://reqres.in/api/users'); // 'POST' or 'PUT'

req.setRequestHeader("Content-Type", "application/json");

req.addEventListener('load', function() {
    const res = JSON.parse(req.responseText);
    console.log(res);
});

req.send(JSON.stringify(user));

Error handling is added in the same way as for a GET request: checking the values of readyState and status of the request object and handling appropriately.

In this case, if the response is successful, the server response code will be 201.

const user = {
    name: "Nicholas Cage",
    address: "Oakwood Street",
}

const req = new XMLHttpRequest();

req.open('POST', 'https://reqres.in/api/users');

req.setRequestHeader("Content-Type", "application/json");

req.addEventListener('load', function() {
    if (req.readyState === 4 && req.status === 201) {
        const res = JSON.parse(req.responseText);
        console.log(res);
    } else {
        console.log("Request error");
    }
});

req.send(JSON.stringify(user));

DELETE request

To make a DELETE request, change the request type to 'DELETE'.

For the API used here, no responseText data is sent back to us. Instead, a 204 status code is returned is the request was successful. If this is the case, we log a success message to the console. Otherwise, you'll want to log an error message.

const req = new XMLHttpRequest();

req.open('DELETE', 'https://reqres.in/api/users/2');

req.addEventListener('load', function() {
    if (req.readyState === 4 && req.status === 204) {
        console.log("Successfully deleted!")
    } else {
        console.log("Request error");
    }
});

req.send();

Related links