How to send GET and POST Ajax API requests in Vanilla JavaScript

Guide to writing JavaScript GET or POST ajax API request without Jquery

Ajax is short for asynchronous JavaScript and XML and is a mechanism for updating a part of a page. It gives you the power to update a part of the page after getting data from the server, thus avoiding refreshing the entire page. Also, implementing partial page updates in this way not only effectively creates a smooth user experience, but also reduces the load on the server.

A basic Ajax request

var xmlhttp= new XMLHttpRequest ();
xmlhttp.open ('GET', 'send-ajax-request-url');
xmlhttp.send (null);

Here, we create an instance of a class that can issue HTTP requests to the server. Then call its open method, where the first parameter is the HTTP request method and the second parameter is the URL of the request page. Finally, we call the send method with a null parameter. If you use the POST request method (here we used GET), the parameters of the send method should contain any data you want to send.

Here is how we handle the server's response

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState !== 4) return;
  if (xmlhttp.status === 200) {
    console.log('Request Response', xmlhttp.responseText);
  }
  else {
    console.log('HTTP error', xmlhttp.status, xmlhttp.statusText);
  }
};

onreadystatechange is asynchronous, then which means it will be called at any time. This type of function is called a callback function-once certain processing is completed, it will be called. In this case, this processing takes place on the server.

The convenient Ajax method is also the reason why many people rely on jQuery, but the Ajax API of native JavaScript is also very powerful, and the basic use is not much different in various browsers, so you can completely encapsulate an Ajax object.

An example of POST Ajax Request

var xmlhttp;
if (window.XMLHttpRequest) {
  xmlhttp = new XMLHttpRequest();
} else {
  xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}

xmlhttp.open('POST', 'send-ajax-request-url', true);
// Set content type according to your data type
xmlhttp.setRequestHeader('Content-Type', 'application/json');
xmlhttp.setRequestHeader('cache-control', 'no-cache');

// if data type is json use JSON stringify
xmlhttp.send(JSON.stringify(data));

// Set request timeout to handle any network error
xmlhttp.timeout = 5000;
xmlhttp.ontimeout = function() {
  console.log('Request Timeout', xmlhttp.responseURL);
};

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState !== 4) return;
  if (xmlhttp.status === 200) {
    let response = '';
    try {
      response = JSON.parse(xmlhttp.responseText);
    } catch (e) {
      response = xmlhttp.responseText;
    }
    console.log('API Response', response);
  }
  else {
    console.log('HTTP error', xmlhttp.status, xmlhttp.statusText);
  }
};

An example of GET Ajax Request

var xmlhttp;
if (window.XMLHttpRequest) {
  xmlhttp = new XMLHttpRequest();
} else {
  xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}

xmlhttp.open('GET', 'send-ajax-request-url', true);
xmlhttp.setRequestHeader('cache-control', 'no-cache');
xmlhttp.send();

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState !== 4) return;
  if (xmlhttp.status == 200) {
    let response;
    try {
      response= JSON.parse(xmlhttp.responseText);
    } catch (e) {
      response= xmlhttp.responseText;
    }
    console.log('Request Response', response);
  }
  else {
    console.log('HTTP error', xmlhttp.status, xmlhttp.statusText);
  }
};

This article mainly introduces examples to explain the method of using native JavaScript to process AJAX requests, so that even if the native API is used instead of the Ajax method in jQuery, friends who need it can refer to this article.