tags:

views:

45

answers:

2

hi,

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??

+2  A: 

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.

XIII
+2  A: 

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

Mark Schultheiss
You should use `ajaxStart` and `ajaxStop` here, otherwise the *first* request to come back (if multiple at once) hides the loader (though the others are still finishing), and each request that's not the first does extra work.
Nick Craver
@Nick Craver - probably true, although I also use this to change the text at times so that I can show a bit more detail if I have multiple going on at once (see the two spans in my div). In a generic circumstance, you are correct however.
Mark Schultheiss