Network request to fetch an API

In jQuery, you can perform network requests using the ajax() function. In JavaScript the equivalent is fetch() native function.

Refer to the following code snippet to learn how to perform network requests through jQuery and vanilla JavaScript:

// Perform network requests using jQuery
$.ajax({
    url: "http://example.com/movies.json",
    type: "POST",
    data: {
        key: value
    },
    success: function (response) {
        // See the response
    },
    error: function (response) {
        // See the error response
    }
});
// Perform network requests using vanilla JavaScript
fetch("http://example.com/movies.json", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({key: value})
}).then(response => {
    // See the response
}).catch(error => {
    // See the error response
});

Another vanilla Javascript is for IE10+:



var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (this.status >= 200 && this.status < 400) {
    // Success!
    var resp = this.response;
  } else {
    // We reached our target server, but it returned an error
  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();