chrizonline
chrizonline

Reputation: 4979

jquery submit and loading gif

im using jquery to submit a php form. during the submission, it will validate for valid fields. so when user click the submit button, im expecting to show the loading gif while it process the form. when it is done, the loading gif fade off.

my jquery submit is as follows:

$(document).ready(function(){
 $("#loadinggif").hide();
 $(function(){
  $("#form").submit(function(){
   $.post("/postform.php", $("#form").serialize(),
   function(data){
    // Put an animated GIF image insight of content
     $("#loadinggif").fadeIn().animate({ opacity: 1.0 },3000).fadeOut();

    if(data.error != null){

     $("#ajax_messagepost").html(data.error);
    }
    else{
     var url = "/confirmation.php";
     $(location).attr('href',url);
    }
   }, "json");

   return false;

  });
 });
});

right now what happen is if the submit button is clicked, the loading gif shows and continue to show even after the data is returned. how do i hide it when data is returned??

Upvotes: 0

Views: 2519

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34196

Put up this to show and hide on any ajax control:

var loadingMessage = 'Please wait loading data for ' + defaulttext;
$(function()
{
    $("#Errorstatus")
    .bind("ajaxSend", function()
    {
        $(this).text(loadingMessage);
        $(this).show();
    })
    .bind("ajaxComplete", function()
    {
        $(this).hide();
    });
});

where #Errorstatus is a span with a background

 <div class="newProcedureErrorStatus ajaxLoading " id="newProcedureErrorStatus">
                    <span id="Errorstatus" class="ui-state-error-text newProcedureErrorStatusText"></span>
                    <span id="Errorstatus2" class="ui-state-error-text newProcedureErrorStatusText">
                    </span>
</div>

the css is:

.ajaxLoading
{
    width: 100%;
    background-image: url("../Images/ajax-loader.indicator.gif");
    background-repeat: no-repeat;
    background-position: left middle;
}

Now, the messages show on any ajax call with the animated gif and the text you put in the spans

Upvotes: 2

Kris van der Mast
Kris van der Mast

Reputation: 16613

Since you're performing ajax in the submit and want the animation to appear and disappear I suggest you use the global ajax helpers in jQuery:

ajaxStart
ajaxStop

Grz, Kris.

Upvotes: 2

Related Questions