trolkura trolkura - 6 months ago 41
Ajax Question

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();'GET', url);

req.onload = function() {
if (req.status == 200) {
} else {
req.onerror = function() {
reject(Error("Network Error"));

ajaxCall('www.testSite').then(x => {
}) // returns html of site

fetch('www.testSite').then(x => {
}) // returns object with information about call

This is what the
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
to return the same thing as a typical AJAX call?


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 => {

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 => {