Home » Php » html – Loading the rest of the page then flushing a loop in its body using PHP

html – Loading the rest of the page then flushing a loop in its body using PHP

Posted by: admin February 25, 2020 Leave a comment

Questions:

I want to load the layout of the page, i.e. header, navigation bar and footer, but implement a long running loop in the body in between the navigation bar and the footer, that flushes what it has done every once in a while. For example:

<!DOCTYPE HTML>
<html>
    <body>
        <header><!--some stuff--></header>
        <nav><!--some stuff--></nav>
        <article>
            <h1>Flushtest</h1>
            <section>
<?php
    for ($i = 0; $i < 5; $i++) {
        echo "Test-$i!<br>";
        flush();
        ob_flush();
        sleep(1);
    }
?>
            </section>
        </article>
        <footer><!--some stuff--></footer>
    </body>
</html>

If I do this, it loads the header and the navigation bar, then every second a new “Test-n” message appears, and when the last test appears, the footer finally appears.
I want the footer to already appear, then load the middle of the page while flushing. Any way to do that?

I tried using AJAX to do it, but either I force it to go very slowly, or it raises a “Too many requests” error. Also, I want the page to still show a ‘loading’ icon in its tab, and AJAX does not do this.

EDIT
Of course, I’ve struggled with this for days, and the day after asking here I’ve found my solution: just use iframes.

How to&Answers: