0

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);
}
0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Just learned this myself a couple months ago. Thought it was pretty cool. =)
Yeah, for sure. I like that it is generic enough that you can pretty well use it anywhere, for pretty well any thing.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.