Get JSON data from an URL

AJAX request using ES6 Promises

by Génesis García Morilla

HTML

<div id="using-fetch"></div>
<div id="using-XMLHttpRequest"></div>

JavaScript

// Note: the url needs https because we request from https
// and the server should allow all origins (Access-Control-Allow-Origin: *)
let $div1_ = document.querySelector('#using-fetch');
let $div2_ = document.querySelector('#using-XMLHttpRequest');

/**
 * Get JSON data from an URL using fetch()
 */
fetch('https://httpbin.org/ip')
  .then(response => {
    if (response.ok) {
      response.json().then(data => {
        $div1_.textContent = JSON.stringify(data);
      });
    } else $div1_.textContent = 'Network response was not ok.';
  })
  .catch(error =>
    $div1_.textContent = 'Fetch error: ' + error
  );

/**
 * Get JSON data from an URL using XMLHttpRequest() and promises
 */
let getJSON = url => {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open('get', url, true); // asynchronous
    xhr.responseType = 'json';
    xhr.onload = () => {
      if (xhr.status === 200) resolve(xhr.response); // then
      else reject(xhr.status); // catch
    };
    xhr.send();
  });
};

getJSON('https://httpbin.org/ip')
  .then(data => {
    $div2_.textContent = JSON.stringify(data);
  })
  .catch(status => {
    $div2_.textContent = 'Error: ' + status;
  });