7

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.

1 Answer 1

15

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" );
               });
1
  • also to add If $.ajax() or $.ajaxSetup() is called with the global option set to false, the .ajaxStart() method will not fire for that particular ajax call.
    – vibs2006
    Commented Feb 6, 2017 at 4:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.