aslamdoctor
aslamdoctor

Reputation: 3935

How to show Loading message instantly while using jquery ajax?

Below is my Ajax code I have made using jQuery Ajax method.

$(".loading_msg").show();
$.ajax({
    type: "POST",
    url: "submit_ops.php?action=submit_form",
    data: $( "#frmMyForm" ).serialize(),
    success: function(result){
        if(result=='Success'){
            $("#msgContainer").html('<div style="color:#3CA322;font-weight:bold;font-size:14px;padding:10px;">Thank you.</div>');
            $("#msgContainer").fadeIn();
        }
        else{
            $("#msgContainer").html('<div style="color:red;font-size:12px;padding:10px;">' + result + '</div>');
            $("#msgContainer").fadeIn();
        }
    },
    error: function(){
        //console.log('error');
    },
    complete: function(){
        //console.log('complete');
        $(".loading_msg").hide();
        $("#submit").attr("disabled", false);
    }

});

So the logic is, whenever the Ajax request is about to made,

  1. the .login_msg container is displayed first

  2. then ajax call made

  3. and when it is completed, again the .loading_msg is hidden.

Now the problem, it is not working smoothly as it should be. So when the ajax call is made, the browser hangs for a seconds but it doesn't show the loading message. But when the request is completed, the login message appears like for half a second and then it goes away as I have set it hidden on request completion.

So I want that the .login_msg should be shown before the request is made.

Any suggestions for this? Thanks in advance.

Upvotes: 0

Views: 6794

Answers (1)

TheVillageIdiot
TheVillageIdiot

Reputation: 40512

try using beforeSend and complete settings of $.ajax:

$.ajax({
    type: "POST",
    url: "submit_ops.php?action=submit_form",
    data: $( "#frmMyForm" ).serialize(),
    beforeSend:function(){
             $(".loading_msg").show();
        }
    complete:function(){
             $(".loading_msg").hide();
        }

    ....
    ....
});

Upvotes: 2

Related Questions