Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch vs. AjaxCall

What is the difference between typical AJAX and Fetch API?

Consider this scenario:

function ajaxCall(url) {   return new Promise(function(resolve, reject) {     var req = new XMLHttpRequest();     req.open('GET', url);      req.onload = function() {       if (req.status == 200) {         resolve(req.response);       } else {         reject(Error(req.statusText));       }     };     req.onerror = function() {       reject(Error("Network Error"));     };     req.send();   }); }  ajaxCall('www.testSite').then(x => {   console.log(x) }) // returns html of site  fetch('www.testSite').then(x => {   console.log(x) }) // returns object with information about call 

This is what the fetch call returns:

Response {type: "cors", url: "www.testSite", status: 200, ok: true, statusText: "OK"…} 

Why does it return different things?

Is there a way for fetch to return the same thing as a typical AJAX call?

like image 496
Darlyn Avatar asked Jul 12 '16 15:07

Darlyn


People also ask

Is fetch Still AJAX?

Ajax is gradually being replaced by functions within JavaScript frameworks and the official Fetch API Standard.

Should I use XMLHttpRequest or fetch?

The Fetch API 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.

Is fetch faster than XHR?

The Fetch API might be faster than XHR # fetch() will be the same as XHR at the network level, but for things like decoding JSON, it can do that work off-thread because the API contract is promise-based up-front. So, the actual API calls aren't any faster.

Should I use fetch or Axios?

Without question, some developers prefer Axios over built-in APIs for its ease of use. But many overestimate the need for such a library. The fetch() API is perfectly capable of reproducing the key features of Axios, and it has the added advantage of being readily available in all modern browsers.


1 Answers

The Fetch API has built in methods for different datatypes.
For just regular text/html you'd use the text() method, which returns a promise as well, and chain it with another then call.

fetch('www.testSite').then( x => {      return x.text(); }).then( y => {     console.log(y); }); 

The built-ins for the returned content is as follows

  • clone() - Creates a clone of a Response object.
  • error() - Returns a new Response object associated with a network error.
  • redirect() - Creates a new response with a different URL.
  • arrayBuffer() - Returns a promise that resolves with an ArrayBuffer.
  • blob() - Returns a promise that resolves with a Blob.
  • formData() - Returns a promise that resolves with a FormData object.
  • json() - Returns a promise that resolves with a JSON object.
  • text() - Returns a promise that resolves with a USVString (text).

It also allows you to send things to the server, or add your own headers etc.

fetch('www.testSite', {     method  : 'post',     headers : new Headers({         'Content-Type': 'application/x-www-form-urlencoded'     }),     body    : new FormData(document.getElementById('myform')) }).then( response => {     return response.json(); // server returned valid JSON }).then( parsed_result => {     console.log(parsed_result); }); 
like image 51
adeneo Avatar answered Sep 19 '22 16:09

adeneo