Implementing loading div in a php page not working

620 views Asked by At

I have a php page which calculate a long process on page load. I have tried to implement a "waiting div" with js - however the page is still waiting for the php calculation to finish and not showing the loading div while it is calculating. here is my code elements order:

<!DOCTYPE html>
<html>
 <head>
        <meta charset="utf-8" />
        <title>My site</title>
        <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

        <link rel="stylesheet" type="text/css" href="/css/style.css">
     <style>
         #load_screen{
             background: #000;
             height: 1600px;
             width: 100%;
         }
         #loading{
             color: #fff;
         }
     </style>

  </head>
  <body>
      <div id="load_screen">
          <div id="loading">calculating path</div>
      </div>
<?php 


 //my php calculation and DB calls
    ?>
    <div id="container" class="container">
</div>
<script>
window.addEventListener("load", function ()
{
var load_screen = document.getElementById("load_screen");
document.body.removeChild(load_screen);
});
</script>

anyone knows why the "loading" div is now showing and waiting for the php page to fully load?

1

There are 1 answers

0
Praveen Kumar Purushothaman On BEST ANSWER

This is slightly not possible in your case. But, when you are using jQuery, stick with jQuery. Replace the following script:

<script>
window.addEventListener("load", function ()
{
var load_screen = document.getElementById("load_screen");
document.body.removeChild(load_screen);
});
</script>

With:

$(document).ready(function () {
  $("#load_screen").remove();
});

The above two methods is for the page load and not for PHP Calculation to complete. You should have a trigger or a call back in the completion, and then attach that event with removal of load screen. So, say if your PHP calculation completes and sends an AJAX Response, with true, then you can remove the loading screen.

$.get("calculate.php", function (res) {
  if (res == "ok")
    $("#load_screen").remove();
});

I now assume that the PHP file has something similar. Source of calculate.php:

<?php
  sleep(5);
  die("ok");
?>

While using the both scripts above, PHP has a delay of 5 seconds (explicitly). After 5 seconds, the load screen will be removed!