Vanilla JavaScript Ajax Promise

Here is a plain ole vanilla JavaScript Ajax Promise request and response. Feel free to copy it, use it, modify it, love it, hate it, destroy it, whatever!

function get(url) {
    // Return a new promise.
    return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();'GET', url);
    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
      } else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    // Make the request

get('your-route-here.json').then(function(response) {
  console.log("Success!", response);
}, function(error) {
  console.error("Failed!", error);
Published: January 12, 2019 2:19 pm Categorized in:

No Comments

Share Your Comments

I value your privacy, your email address will not be published or shared.

This site uses Akismet to reduce spam. Learn how your comment data is processed.