AlexScalar
AlexScalar

Reputation: 1927

Do something immediately after posting in jQuery

I am new to jQuery, so I was wondering, how can I display something immediately after posting. At this moment I have something like this.

$('#cur_select').on('change', function() {
    $.post( "getTable.php", { value: this.value }).done(function( data ) 
    {
        $("#mytable").html(data);
    });
});

It takes some time to get the data from PHP, so I want to notify the user (by changing text of a label), that the site is in the process of getting the data. Where can I put such code here?

Upvotes: 0

Views: 438

Answers (3)

user3617709
user3617709

Reputation: 46

Please go through the two functions ajaxStart and ajaxComplete in jquery. These two functions will help you to do the change like showing a spinner or showing some text to the user before the processing and hide it once the data is retrieved. Thank you.

Upvotes: 0

Michael Beeson
Michael Beeson

Reputation: 2875

$.post will update when it updates. The callback function that you have after .done() will be called once $.post is finished. As that is happening, javascript will carry on. So whatever you want to do (maybe have a spinner animation within #mytable as it waits for its data) can be placed immediately after the $.post, or even before.

$('#cur_select').on('change', function() {
    $.post( "getTable.php", { value: this.value }).done(function( data ) 
    {
        $("#mytable").html(data);
    });

    $("#mytable").css("background-image", "url(/myLoadingSpinner.gif)"); 
});

Upvotes: 1

someRandomSerbianGuy
someRandomSerbianGuy

Reputation: 491

You can do that just before you do POST call or you can put your code just after POST call (because POST.done is asynchronous and code is moving immediately along).

$('#cur_select').on('change', function() {
    //Here
    $.post( "getTable.php", { value: this.value }).done(function( data ) 
    {
        $("#mytable").html(data);
    });
    //Or here
});

Upvotes: 2

Related Questions