user5740843 user5740843 - 1 month ago 11
Javascript Question

jQuery loading img while exec Python script PHP

I'm fumbling around a little bit with jQuery and Python and I was trying to show a very simple page displaying a loading img while a somewhat length python script gets the information I need to display.

Of course, when the Python script is ready, I was hoping to hide the loading image and display the results of the Python script in it's place.

So far, I was able to piece this together with some Google help for my webpage:

<html>
<head>
<img id="img" src="loader.gif">
<script src="assets/js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
url: "http://localhost/test.py";
$.post(url, function(data){
$("#id").html(data);
});
$("#img").hide();
});
</script>
</head>
</html>


Any help would be greately appreciated. Thanks!

Answer

This part

$("#id").html(data);

means that jQuery is filling the element with the id "id" with the response from your Python script. The problem is that you don't have an element that has id="id".

What you also want to do is to put $("#img").hide(); inside your success handler of $.post. This way the image is hidden when $.post has finished. With your current code it's hidden immediately because $.post is an asynchronous request and thus any other code won't wait for it.

Your code should look something like this:

<html>
<head>
    <img id="img" src="loader.gif">
    <div id="id"></div>
    <script src="assets/js/jquery-1.9.1.min.js"></script>
    <script>
    $(document).ready(function() {
       url: "http://localhost/test.py";
       $.post(url, function(data){
          $("#id").html(data);
          $("#img").hide();
       });
    });
   </script>
</head>
</html>

Note the <div> I've added (you can replace it with any other HTML element you want).

UPDATE

There is a chance that your $.post request fails due to different reasons. Currently, you only have a success handler which only gets called when the request was successful. You can add an "unsuccess" handler like this:

 $.post(url, function(data){
    $("#id").html(data);
    $("#img").hide();
 })
 .fail(function(response) {
     alert('Error: ' + response.responseText);
     // .. do something else .. 
 });