Create a JavaScript AJAX GET request

Create a simple function that sends an AJAX GET request and returns a JSON response.

Code

Send a GET request through AJAX with a JSON response.

  • ES5 version using XMLHttpRequest
  • ES6 version using fetch()

JavaScript ES5 using XMLHttpRequest

Sometimes you need a legacy version for compatibility with legacy code; use the ES5 version.

Simple:

function sendGetHttpRequest(url) {
    var request = new XMLHttpRequest();
    request.open("GET", url);
    request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    request.send();
}

With callbacks:

function sendGetRequest(url) {
    var xhr = new XMLHttpRequest();

    xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
            console.log(xhr.response);
        } else {
            console.error(xhr.statusText);
        }
    };

    xhr.onerror = function() {
        console.error(xhr.statusText);
    };

    xhr.open("GET", url);
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.send();
}

JavaScript ES6 using fetch()

function sendGetRequest(url) {
    fetch(url)
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error(error));
}