Search code examples
javascriptphpspinnerclassloader

basic loader spinner inside php during call to remote server


I want to add a loading spinner while my remote script is running and my frontend page is in "waiting for ..." state. I only have 1 php page and one CSS . ( for the moment still in tests so I have not split script page and html page yet).

I have the following css for the loader :

Style.css edited to replace the "." with "#"

#loader {
    border: 16px solid #f3f3f3; /* Light grey */
    border-top: 16px solid #3498db; /* Blue */
    border-radius: 50%;
    width: 120px;
    height: 120px;
    animation: spin 2s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

My page looks like this ( after cleaning it ) : EDIT with webbm comments

<!DOCTYPE html>
<html>
<head>
  <title> BETA APP HOME PAGE </title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
  <link rel="stylesheet" href="CSS/style.css">
</head>
<body>

<div id="loader"></div>

<?php
if (isset($_POST['STARTVISUREC']))
{

   echo '<script>console.log("End loader spinner")</script>';
// making appearing the spinner before the call to remote server. 
    echo '<script language="javascript">';
    echo 'document.getElementById("loader").style.display="inline"';
    echo '</script>';

// calling remote APP in BE server. 
$remotstarter = file_get_contents('http://192.168.56.154/WEBAPP/wa_start.php');

   echo '<script>console.log("End loader spinner")</script>';
// making disappearing the spinner after the call to remote is finished. 
    echo '<script language="javascript">';
    echo 'document.getElementById("loader").style.display="hidden"';
    echo '</script>';

}
if (isset($_POST['STARTFACEREC']))
{
// calling local script for other usage. 
shell_exec("sudo python  AppPy/cgi-bin/test.py");
echo("Off");
}
?>

<form method="post">
<button name="STARTVISUREC">START VISU REC</button>&nbsp;
<button name="STARTFACEREC">START FACE REC</button><br><br>
</form> 
<script>
</script>
</div>
</div>
<div style="margin-left:15%;padding:1px 16px;height:10px;">
</div>
</body>
</html>

still not OK The loading spinner is not appearing


Solution

  • For your case specifically, you could echo a script tag.

    <?php
     echo '<script language="javascript">';
     echo 'document.getElementById("loader").style.display="inline"';
     echo '</script>';
    ?>
    

    Note that I switched around the usage of " and '. Check out the echo documentation for why this is useful https://secure.php.net/manual/en/function.echo.php

    I recommend you look into ajax queries which can allow you to perform the javascript actions inside of javascript based on the server response.

    Here's a basic example: https://www.w3schools.com/php/php_ajax_php.asp