HTTP GET request in JavaScript?


I need to do an HTTP GET request in JavaScript. What's the best way to do that?

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

5/12/2020 11:27:04 AM

Accepted Answer

Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:

function httpGet(theUrl)
    var xmlHttp = new XMLHttpRequest(); "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:

Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.

You should make an asynchronous request and handle the response inside an event handler.

function httpGetAsync(theUrl, callback)
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
    }"GET", theUrl, true); // true for asynchronous 
4/3/2019 3:43:08 PM

In jQuery:

    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);

Lots of great advice above, but not very reusable, and too often filled with DOM nonsense and other fluff that hides the easy code.

Here's a Javascript class we created that's reusable and easy to use. Currently it only has a GET method, but that works for 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)
        } "GET", aUrl, true );            
        anHttpRequest.send( null );

Using it is as easy as:

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

The new window.fetch API is a cleaner replacement for XMLHttpRequest that makes use of ES6 promises. There's a nice explanation here, but it boils down to (from the article):

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
}).catch(function() {

Browser support is now good in the latest releases (works in Chrome, Firefox, Edge (v14), Safari (v10.1), Opera, Safari iOS (v10.3), Android browser, and Chrome for Android), however IE will likely not get official support. GitHub has a polyfill available which is recommended to support older browsers still largely in use (esp versions of Safari pre March 2017 and mobile browsers from the same period).

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

Here's a link to the spec


Using ES7 async/await, this becomes simply (based on this Gist):

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

A version without callback

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

Here is code to do it directly with JavaScript. But, as previously mentioned, you'd be much better off with a JavaScript library. My favorite is jQuery.

In the case below, an ASPX page (that's servicing as a poor man's REST service) is being called to return a JavaScript JSON object.

var xmlHttp = null;

function GetCustomerInfo()
    var CustomerNumber = document.getElementById( "TextBoxCustomerNumber" ).value;
    var Url = "GetCustomerInfoAsJson.aspx?number=" + CustomerNumber;

    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = ProcessRequest; "GET", Url, true );
    xmlHttp.send( null );

function ProcessRequest() 
    if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) 
        if ( xmlHttp.responseText == "Not found" ) 
            document.getElementById( "TextBoxCustomerName"    ).value = "Not found";
            document.getElementById( "TextBoxCustomerAddress" ).value = "";
            var info = eval ( "(" + xmlHttp.responseText + ")" );

            // No parsing necessary with JSON!        
            document.getElementById( "TextBoxCustomerName"    ).value = info.jsonData[ 0 ].cmname;
            document.getElementById( "TextBoxCustomerAddress" ).value = info.jsonData[ 0 ].cmaddr1;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]