Daniel
Daniel

Reputation: 4342

show loading status with ajax call

I'm looking for a JavaScript solution to show some sort of status while an ajax request is taking place. I tried document.getElementById("status").innerHTML = "<h2>Loading....</h2>"; but that didn't work. Any ideas?

function codesDelete(id) {
    var ajax;
    if (window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
    } else {
        ajax = new ActiveXObject("Microsoft.XMLHTTP");
    }

    ajax.onreadystatechange = function() {
        if (ajax.readyState === 4 && ajax.status === 200) {
            document.getElementById("status").innerHTML = "<h2>Data Deleted!</h2>";
        }
    }

    // this is what i tried
    document.getElementById("status").innerHTML = "<h2>Loading....</h2>";


    ajax.open("GET", "code.php?id=" + id, true);
    ajax.send();

    setTimeout(function() {
        document.getElementById("status").style.display = "none";
    }, 3000);
}

Upvotes: 0

Views: 894

Answers (2)

Paul Richter
Paul Richter

Reputation: 11072

Another method you could do is to use the beforeSend and complete callbacks on jQuery.ajax, like so:

$.ajax({
    beforeSend:function(){
        // Create and insert your loading message here as you desire
        // For example, a version of what you were trying to do would be:
        $("#status").html("<h2>Loading....</h2>");
    },
    // ... whatever other things you need, such as a success callback, data, url, etc
    complete: function(){
       // Remove your loading message here, for example:
       $("#status").html("");
    }
});

As the names suggest, beforeSend will be executed before the AJAX call is made. Complete will execute, regardless whether the AJAX succeeded or failed, after the call is finished.

Upvotes: 1

Yatrix
Yatrix

Reputation: 13775

You can use JQuery's when/done. Start your status indicator and then use when/done like this:

// start the status indicator wherever it's appropriate    
StartStatusIndicator();

//Make your ajax call
$.when($.ajax({
    type: "POST",
    ...more stuff...
    success: function (json) {
        ...even more stuff...
    }
})).done(function () {
    KillYourStatusIndicator();
});

The code inside done gets fired when the ajax call is finished.

Upvotes: 1

Related Questions