How to do equivalent in JavaScript?

How to do equivalent in JavaScript?
0.0 0

#1

How can I write the equivalent of an AJAX request in jQuery, specifically this-

$.ajax({
            url: 'someUrl',
            type: 'GET',
            success: function(data) {
                someFunction(data)
       }
})

in plain JavaScript (using XMLHttpRequest)


#2

Ew. Don’t. Use fetch instead as it will be replacing the XHR dance as the new standard.

fetch('someUrl')
.then(function(response) {
    if(response.ok) { //only send data to the success handler if it's got a status of 2XX
        return response.json();
    } else {
        throw { message: "ERROR!1!", data: response }; //there are many ways to do this
    }
}).then(function(data) {
    //success is handled in the 'then' method's first parameter
    someFunction(data);
}, function(error) {
    //thrown errors (404, 500, etc) are handled in the 'then' method's second parameter
    handleThrownError(error);
}).catch(function(error) {
    //the 'catch' method handles network errors, but not server errors
    //example: if 'fetch' were not able to send a request, this would be invoked
    //however, if you get a 404, 500, or some other error response, it would be handled above
  handleNetworkError(error);
})

#3

Wow, this is undoubtedly easier than XHR! Is this ES7 syntax? I’ve never seen this before.


#4

Nope! That’s just the promise API. Otherwise, that’s all good ol’ fashioned ES5.


#5

If you want to use jquery you can do so like this:

$.get ("url.com").done (function (data){ ...});

You can also use it with promises:

$.get ("url.com").then (function(data){ ...});

You can chain those “then” function together as well.