API call in Javascript

API call in Javascript

1 Like


Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.

What is AJAX?

AJAX = Asynchronous JavaScript And XML.

AJAX is not a programming language.

AJAX just uses a combination of:

  • A browser built-in XMLHttpRequest object (to request data from a web server)
  • JavaScript and HTML DOM (to display or use the data)

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object can be used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

XMLHttpRequest Object Methods

XMLHttpRequest Object Properties

Send a Request To a Server:

xhttp.open(“POST”, “demo_post2.asp”, true);
xhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);



By sending asynchronously, the JavaScript does not have to wait for the server response, but can instead:

  • execute other scripts while waiting for server response
  • deal with the response after the response is ready

The onreadystatechange Property

With the XMLHttpRequest object you can define a function to be executed when the request receives an answer.

xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(“demo”).innerHTML = this.responseText;
xhttp.open(“GET”, “ajax_info.txt”, true);

Server Response:
The readyState property holds the status of the XMLHttpRequest.

The onreadystatechange property defines a function to be executed when the readyState changes.

The status property and the statusText property holds the status of the XMLHttpRequest object.

function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(“demo”).innerHTML =
xhttp.open(“GET”, “info.txt”, true);

Fetch API:

fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

Basic Fetch Request

Let’s start by comparing a simple example implemented with an XMLHttpRequest and then with fetch. We just want to request a URL, get a response and parse it as JSON.


An XMLHttpRequest would need two listeners to be set to handle the success and error cases and a call to open() and send()


Our fetch request looks a little like this:

fetch('./api/some.json')  .then(    function(response) {      if (response.status !== 200) {        console.log('Looks like there was a problem. Status Code: ' +          response.status);        return;      }      // Examine the text in the response      response.json().then(function(data) {        console.log(data);      });    }  )  .catch(function(err) {    console.log('Fetch Error :-S', err);  });

We start by checking that the response status is 200 before parsing the response as JSON.

The response of a fetch() request is a Stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.

Response Metadata

In the previous example we looked at the status of the Response object as well as how to parse the response as JSON. Other metadata we may want to access, like headers, are illustrated below.

fetch('users.json').then(function(response) {    console.log(response.headers.get('Content-Type'));    console.log(response.headers.get('Date'));    console.log(response.status);    console.log(response.statusText);    console.log(response.type);    console.log(response.url);});

Response Types

When we make a fetch request, the response will be given a response.type of “basic”, “cors” or “opaque”. These types indicate where the resource has come from and can be used to inform how you should treat the response object.

When a request is made for a resource on the same origin, the response will have a basic type and there aren’t any restrictions on what you can view from the response.

If a request is made for a resource on another origin which returns the CORs headers, then the type is cors. cors and basic responses are almost identical except that a cors response restricts the headers you can view to Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, and Pragma.

An opaque response is for a request made for a resource on a different origin that doesn’t return CORS headers. With an opaque response we won’t be able to read the data returned or view the status of the request, meaning we can’t check if the request was successful or not.

You can define a mode for a fetch request such that only certain requests will resolve. The modes you can set are as follows:

  • same-origin only succeeds for requests for assets on the same origin, all other requests will reject.
  • cors will allow requests for assets on the same-origin and other origins which return the appropriate CORs headers.
  • cors-with-forced-preflight will always perform a preflight check before making the actual request.
  • no-cors is intended to make requests to other origins that do not have CORS headers and result in an opaque response, but as stated, this isn’t possible in the window global scope at the moment.

To define the mode, add an options object as the second parameter in the fetch request and define the mode in that object:

fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})  .then(function(response) {    return response.text();  })  .then(function(text) {    console.log('Request successful', text);  })  .catch(function(error) {    log('Request failed', error)  });

POST Request

It’s not uncommon for web apps to want to call an API with a POST method and supply some parameters in the body of the request.

To do this we can set the method and body parameters in the fetch() options.

fetch(url, {    method: 'post',    headers: {      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"    },    body: 'foo=bar&lorem=ipsum'  })  .then(json)  .then(function (data) {    console.log('Request succeeded with JSON response', data);  })  .catch(function (error) {    console.log('Request failed', error);  });
1 Like