JavaC3code
JavaC3code

Reputation: 159

Is a get request possible with javascript?

I was wondering if it was possible to make a GET request with javascript, so it can update text without refreshing the page.

If this is possible, how can I make a get request with javascript & get the result/decode it from json?

I tried this from a past question:

function updateButton(){

    var xmlHttp = null;

    xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", false);
    xmlHttp.send(null);
    document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
}

And, it completely stops the main thread, making the website unresponsive. What is wrong?

Upvotes: 0

Views: 75

Answers (3)

XLR
XLR

Reputation: 309

var isAjax=false;
function updateButton(){
     if(!isAjax) { //Stops the user making a million requests per minute
        isAjax=true;
        var xmlHttp = null;

        xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
        xmlHttp.send(null);
        document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
        isAjax=false;
    }
}

OR jQuery...

$("#btnUpdate").click(function(){
    $.get("http://xxxx.com/getSpecialSale.php", function(data, status){
        $("#dicebutton").html(data);
    });
});

Upvotes: 1

Philipp
Philipp

Reputation: 15629

Currently you set the async parameter to false, so the request is sent to the server and the browser waits for the response. To make an async request, just pass true as thrid param to open

xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);

in addition to that, you have to register an callback, which waits for the response (and maybe to handle errors..)

xmlHttp.onload = function (e) {
    if (xmlHttp.readyState === 4) {
        if (xmlHttp.status === 200) {
            console.log(xmlHttp.responseText);
        } else {
           console.error(xmlHttp.statusText);
        }
    }
};
xmlHttp.onerror = function (e) {
    console.error(xmlHttp.statusText);
};

In addition to that a note from the mozilla docs

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.

Upvotes: 1

James
James

Reputation: 22247

If you want to use async you will need some code modifications, ie the stuff that happens after the response completes needs to be in a callback function as follows:

function updateButton(){

    var xmlHttp = null;

    xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
    xmlHttp.onload = function () {
      document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
    };
    xmlHttp.send(null);

}

Upvotes: 0

Related Questions