How do I use ajaxStart to show the loader?

I have a webpage that runs a python script using the shell_exec command. I'd like a boot counter, "Please wait for this page to load" message to show while the python script is running, after which it will be done for the rest of the rendered HTML.

I found what seems to be a good solution on this StackOverflow question ... but I'm so new to ajax that I don't know how to use this 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 it didn't work. Do I need to call ajax to trigger ajaxStart? How can I call it? Should I wrap shell_exec in ajax code?

Thanks a bunch.

+3


source to share


1 answer


Whenever an Ajax request is sent, jQuery checks for other outstanding Ajax requests. If none of these are executed, jQuery fires the ajaxStart event.

Load the gif image as shown below.

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

      

Hide that loading div first (because the loading image should show when the ajax request is 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>

      

See jQuery documentation for details

Do I need to call ajax to do ajaxStart? How can I call it?



Yes, when you fire an ajax request then only ajaxStart is automatically triggered.

There are several ways for ajax with jquery, below I provide the upload function.

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

      

the output of some_file.py will be inserted into a div with the result of the class name.

To trigger the load event, you can use a click on the button or any other as needed.

               $( ".trigger" ).click(function() {
                  $( ".result" ).load( "some_file.py" );
               });

      

+5


source







All Articles