DannyD
DannyD

Reputation: 2901

how can I show my loading icon after my ajax is finished

I have a simple javascript function like so:

function showHint() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            //extract data here

        }
    }

    xmlhttp.open("GET", "articles.php?q=" + cat + "&year1=" + start_year + "&year2=" + end_year, true);

    xmlhttp.send();

}

I want to be able to show my loading icon after the ajax finishes. I show my loading icon at the very beginning of my js by using:

$.mobile.loading("show");

which shows the icon nicely (using jquery mobile). However, I need to only hide the icon after the ajax is completely finished. I've attempted to use a .done() in jQuery like this but I don't think I'm using it properly:

xmlhttp.onreadystatechange.done(function(){
    $.mobile.loading("hide");
});

Upvotes: 1

Views: 442

Answers (1)

Satpal
Satpal

Reputation: 133453

You need to use it onreadystatechange callback function.

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4) {
         $.mobile.loading("hide");
    }
}

As you are already using . You can simply use jQuery.get() like

$.mobile.loading("show");
$.get("articles.php?q=" + cat + "&year1=" + start_year + "&year2=" + end_year, function(data) {
    //Do something
}).done(function() {
    $.mobile.loading("hide");
});

Upvotes: 5

Related Questions