Coder Perfect

In JavaScript, how can I make an HTTP GET request?

Problem

In JavaScript, I need to do an HTTP GET request. What is the most effective method for accomplishing this?

I need to accomplish this in a dashcode widget for Mac OS X.

Asked by mclaughj

Solution #1

An XMLHttpRequest object is provided by browsers (including Dashcode) that can be used to make HTTP requests using JavaScript:

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

However, synchronous requests are discouraged and will generate a warning along the lines of:

Make an asynchronous request and deal with the response in an event handler.

function httpGetAsync(theUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}

Answered by Joan

Solution #2

The new window.fetch API, which uses ES6 promises, is a better replacement for XMLHttpRequest. There’s a wonderful explanation here, but (from the article) it boils down to:

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function() {
  console.log("Booo");
});

The current updates have improved browser support (works in Chrome, Firefox, Edge (v14), Safari (v10.1), Opera, Safari iOS (v10.3), Android browser, and Chrome for Android), but IE is unlikely to receive official support. A polyfill is provided on GitHub to support outdated browsers that are still widely used (esp versions of Safari pre March 2017 and mobile browsers from the same period).

I suppose it depends on the nature of the project whether this is more convenient than jQuery or XMLHttpRequest.

The specification can be found at https://fetch.spec.whatwg.or

Edit:

This becomes simple (based on this Gist) when using ES7 async/await:

async function fetchAsync (url) {
  let response = await fetch(url);
  let data = await response.json();
  return data;
}

Answered by Peter Gibson

Solution #3

In jQuery:

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);

Answered by Pistos

Solution #4

There’s a lot of good advice above, but it’s not very reusable, and it’s typically riddled with DOM nonsense and other fluff that obscures the simple code.

Here’s a reusable and easy-to-use Javascript class we made. It only has a GET method right now, but that’s fine with us. Adding a POST shouldn’t tax anyone’s skills.

var HttpClient = function() {
    this.get = function(aUrl, aCallback) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function() { 
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                aCallback(anHttpRequest.responseText);
        }

        anHttpRequest.open( "GET", aUrl, true );            
        anHttpRequest.send( null );
    }
}

It’s as simple as this to use it:

var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
    // do something with response
});

Answered by tggagne

Solution #5

A version without callback

var i = document.createElement("img");
i.src = "/your/GET/url?params=here";

Answered by aNieto2k

Post is based on https://stackoverflow.com/questions/247483/http-get-request-in-javascript