Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Fetch API and XMLHttpRequest

4.43/5 (5 votes)
29 Jan 2017CPOL 9.4K  
Access the API using the promise HTTP

Introduction

Ajax changed the way of the modern web application loading partially and most of the applications are using Ajax. It can post or pull data asynchronous without reloading the entire page.

XMLHttpRequest

JavaScript
var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {

            if (xhr.readyState == XMLHttpRequest.DONE) {

                console.log(xhr.response);
            }
        }

        xhr.open('GET', 'http://localhost:801/api/Person', true);

        xhr.send(null);  

The above code may not work in some browser for the safe we will be using the Jquery library.

JavaScript
$.ajax({
          url: 'http://localhost:801/api/Person',
          method: 'Get',
          success: function (data) {
              console.log(data);
          },
          error: function (data) {
              console.log('error');
          }
      });

The fetch method is similar to XMLHttpRequest, whereas Fetch is a promise based asynchronous http networking. It is a clean and easy way to access the API. The browsers supported are Firefox 39 and above and chrome 42 and above. For all other versions of browsers, we can use the alternate Fetch Polyfill (https://github.com/github/fetch):

JavaScript
fetch('http://localhost:801/api/Person').then(x => {

            return x.json();

        }).then(y => {

            console.log(y);

        });

Adding header in the fetch API.

JavaScript
var myHeaders = new Headers();
    var myInit = { method: 'GET',
        headers: myHeaders,
        mode: 'cors'}
    fetch('http://localhost:801/api/Person',myInit)
    .then(function(response) {
        return response.blob()
    });

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)