Show "loading" animation on button click

29

I want to do something very simple. I have one button in my page.

<form action="/process" method="POST">
   <input class="btn btn-large btn-primary" type="submit" value='Analyze Topics'>
    </form>

Now what I want is when the user presses this submit button. It shows that "loading" gif animation until it gets the response from server.

But I have been struggling since long time.

How do I implement this?

This question is tagged with jquery html css ajax

~ Asked on 2013-03-08 06:24:26

The Best Answer is


39

If you are using ajax then (making it as simple as possible)

  1. Add your loading gif image to html and make it hidden (using style in html itself now, you can add it to separate CSS):

    <img src="path\to\loading\gif" id="img" style="display:none"/ >
    
  2. Show the image when button is clicked and hide it again on success function

    $('#buttonID').click(function(){
      $('#img').show(); //<----here
      $.ajax({
        ....
       success:function(result){
           $('#img').hide();  //<--- hide again
       }
    }
    

Make sure you hide the image on ajax error callbacks too to make sure the gif hides even if the ajax fails.

~ Answered on 2013-03-08 06:30:37


7

try

$("#btnId").click(function(e){
 e.preventDefault();
 //show loading gif

 $.ajax({
  ...
  success:function(data){
   //remove gif
  },
  error:function(){//remove gif}

 });
});

EDIT: after reading the comments

in case you decide against ajax

$("#btnId").click(function(e){
     e.preventDefault();
     //show loading gif
     $(this).closest('form').submit();
});

~ Answered on 2013-03-08 06:27:31


Most Viewed Questions: