Click here to Skip to main content
15,902,939 members
Articles / Programming Languages / Javascript
Tip/Trick

Fetch API and XMLHttpRequest

Rate me:
Please Sign up or sign in to vote.
4.43/5 (5 votes)
29 Jan 2017CPOL 9.3K   4  
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)


Written By
Team Leader Aspire Systems
India India
Having 12+ years of experience in IT Industry and having Masters Degree in Information Technology.

Personal Blog : https://krishna-kv.com

Comments and Discussions

 
-- There are no messages in this forum --