Load page while PHP is executing

28,971

Solution 1

The main way you can accomplish this is by using AJAX and multiple pages. To accomplish this, the first page should not do any of the processing, just put the loading image here. Next, make an AJAX request, and once the request is finished, you can show the results on the page or redirect to a different page.

Example:

File 1 (jQuery must be included also), put this in the body along with the loader animation:

<script language="javascript" type="text/javascript">
$(function(){
    var mydata = {};
    $.post('/myajaxfile.php', mydata, function(resp){
        // process response here or redirect page
    }, 'json');
});
</script>

Update: Here is a more complete example based on your code. This has not been tested and needs to have the jQuery library included, but this should give you a good idea:

File 1: file1.html

</head>
 <body>
 <?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
 ?>
 <!-- Include jQuery here! Also have the loading animation here. -->
 <script type="text/javascript">
$(function(){

    $.get('/file2.php?Lat=<?php echo $lat; ?>&Lon=<?php echo $long; ?>', null, function(resp){
        // resp will have the data from file2.php
        console.log(resp);
        console.log(resp['min_sec_array']);
        console.log(resp['main']);

        // here is where you will setup the graph 
        // with the data loaded
        <!--Plot function-->
    }, 'json');

});

</script>


 <div id=graph>
 </div>
 </body
 </html>

File 2: file2.php I'm not sure if you needed the $min_sec_array, but I had this example return that as well as the main data you were using before.

$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');

//Pulling in hourly data to plot temp vs time
$i=0;
$main = array();
$array=array();
while ($i<=100)
{
    $main[] = array((strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000), $weather_hourly->data->parameters->temperature->value[$i]);
    $value = $weather_hourly->data->parameters->temperature->value[$i];
    array_push($array,$value);
    $i++;
}
foreach ($array as $key => $value) 
{
    $min_sec_array[] = (string) $value;
}


echo json_encode(array(
    'min_sec_array' =>$min_sec_array,
    'main' => $main
));

exit();

?>

Solution 2

I would recommend not to do this with plain html and php if u expect it modify the page after it is loaded. Because php is server side processing, so it is executed before the page is send to the user. U need Javascript. Using Javascript will enable u to dynamically add or remove html elements to or from the DOM tree after the page was send to the user. It is executed by the users browser.

For easier start I would recommend jQuery, because there are lots of tutorials on such topics.

JQuery

JQuery learning center

A small example:

HTML

<head>
    <meta charset="utf-8" />
    <title> </title>
    <script type="text/javascript" src="js/lib/jquery-1.9.1.js"></script>
</head>
<body>
    <h1>Addition</h1>
    <div id="error_msg"> </div>
    <div id="content">
        <!-- show loading image when opening the page -->
        <img src="images/loading.gif"/>
    </div>
    <script type="text/javascript">
       // your script to load content from php goes here
    </script>
</body>

this will be nothing more then the following until now:


enter image description here


adding the following php file

<?php

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];

$result = $num1 + $num2;

echo '<p>Calculating '.$num1.' + '.$num2.' took a lot of time, but finally we were able to evaluate it to '.$result.'.</p>'
     .'<p> '.$num1.' + '.$num2.' = '.$result.'</p>';

 ?>

wont change anything of the html, but adding javascript/ Jquery inside the HTML will be kind of connection between static html and server side php.

$(document).ready(function(){
    $.ajax({        // call php script
        url: 'php/script.php?num1=258&num2=121',
        type:'GET',
        timeout: 500,
        contentType: 'html'
    }).success(function(data){
            // remove loading image and add content received from php 
        $('div#content').html(data);

    }).error(function(jqXHR, textStatus, errorThrown){
            // in case something went wrong, show error
        $('div#error_msg').append('Sorry, something went wrong: ' + textStatus + ' (' + errorThrown + ')');
    });
});

This will change your page to show the loading animation until the php script returns its data, like:


enter image description here


So you can setup the whole page in plain html, add some loading gifs, call several php scripts and change the content without reloading the page itself.

Share:
28,971

Related videos on Youtube

tyler
Author by

tyler

Here to learn and share what I know.

Updated on December 29, 2020

Comments

  • tyler
    tyler over 3 years

    What Im trying to do: Display a loading gif or text... at the very least show a black screen before and during the time the php is being executed.

    What I have tried.

    I have tested using flush () and I get nothing until the entire php process is finished. I dont particularly like this concept either but I'll take anything.

    I am considering using two pages to accomplish this though the current project is nearly complete and would take some time to consolidate the scattered html/php code.

    Currently I'm doing 3-simpleXML_load_file(), 1-include(), 1-file_get_contents() I have javascript function plotting data from one of the simpleXML_Load_file()...

    Im up for moving parts of the code to a different file but it's a big task. So id like some advise or suggestions on how to proceed.

    If I need to elaborate more just ask!

    Thanks, JT

     <html>
     <head>
     <?php
    $lat = $_POST['Lat'];
    $long = $_POST['Lon'];
     $weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
     ?>
     <script type="text/javascript">
    
     <!--Plot function-->
     $(function() 
     {
     var d = 
     [
    <?php
    //Pulling in hourly data to plot temp vs time
    $i=0;
    $array=array();
    while ($i<=100)
    {
        echo '['. (strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000) .','.$weather_hourly->data->parameters->temperature->value[$i] .'],';
        $value = $weather_hourly->data->parameters->temperature->value[$i];
        array_push($array,$value);
        $i++;
    }
        foreach ($array as $key => $value) 
        { 
                        $value = (string) $value;
                        $min_sec_array[] = $value;
        }
    ?>
    
    </script>
     </head>
     <body>
     <div id=graph>
     </div>
     </body
    
    • tyler
      tyler almost 11 years
      I added a very non working but you get the idea code example
  • tyler
    tyler almost 11 years
    mind showing me a simple example of how I would go about loading in a php file's data
  • tyler
    tyler almost 11 years
    mind showing me a simple example of how I would go about loading in a php file's data
  • tyler
    tyler almost 11 years
    I havent had any luck getting flush to work though im wiling to try again!
  • tyler
    tyler almost 11 years
    The first line within my PHP is currently ob_start(); echo '<img src="pics/loading.gif">'; ob_end_flush();
  • tyler
    tyler almost 11 years
    so this would append File 1 with File 2 html where?
  • Seth
    Seth almost 11 years
    @tman I'm afraid I don't understand specifically what you are trying to do with the 2 scripts. Could you post the actual code so we can see what you are trying to do?
  • tyler
    tyler almost 11 years
    Still seems to finish the entire execution of the php
  • tyler
    tyler almost 11 years
    Id love to see your responce to think problem!
  • sailingthoms
    sailingthoms almost 11 years
    I added a small example, I hope it helps u.