Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ajaxStart to show loading spinner?

Tags:

ajax

I have a webpage that runs a python script with the command shell_exec. I'd like for a loading spinner, the 'Please wait while this page loads' sort of message, to show while the python script is running, then after it is done for the rest of the echo'd HTML to show.

I found what seems like a good solution at https://stackoverflow.com/a/68503/4630491 but I am so new to ajax that I don't know how to use the solution. I tried doing

<div id="loadingDiv">Please wait while this page loads.</div>
<script>var $loading = $('#loadingDiv').hide();
$(document)
  .ajaxStart(function () {
    $loading.show();
  })
  .ajaxStop(function () {
    $loading.hide();
  });
</script>

but this did not work. Do I need to call ajax to execute the ajaxStart? How would I call it? Should I wrap the shell_exec in ajax code?

Thanks a bunch.

like image 281
Max Avatar asked Jul 03 '15 05:07

Max


People also ask

How to Show loading Spinner in Ajax?

Answer: Use the ajaxStart() and ajaxStop() MethodWhile working with Ajax, showing a loading spinner or displaying a message with some animation like "Loading... Please Wait" is popular way to indicate the user that Ajax request is in progress.


1 Answers

Whenever an Ajax request is about to be sent, jQuery checks whether there are any other outstanding Ajax requests. If none are in progress, jQuery triggers the ajaxStart event.

Have a loading gif image like shown below

           <div id="loading">
                <img src="loading.gif" />  
           </div>

First hide this loading div(because loading image have to be shown when ajax request is about to sent).

              <script>
                   var $loading = $('#loading').hide();
                   //Attach the event handler to any element
                   $(document)
                     .ajaxStart(function () {
                        //ajax request went so show the loading image
                         $loading.show();
                     })
                   .ajaxStop(function () {
                       //got response so hide the loading image
                        $loading.hide();
                    });
              </script>

For more see at jQuery documentation

Do I need to call ajax to execute the ajaxStart? How would I call it?

Yes when you triggered a ajax request then only ajaxStart will get triggered automatically.

For ajax there are multiple ways with jquery, below I am giving with load function.

               $( ".result" ).load( "some_file.py" );

some_file.py output will inserted into div with class name result.

To trigger the load event you can use button click or any other as need.

               $( ".trigger" ).click(function() {
                  $( ".result" ).load( "some_file.py" );
               });
like image 177
Manohar Gunturu Avatar answered Sep 21 '22 18:09

Manohar Gunturu