I need to display most of a page's content before outputting the content from a function. The function takes a while to execute, and returns some content for the page. I need the rest of the page to display first, then run the function, and then 'insert' the function output.
It would seem that I'd need to use ob_start at the beginning of the function, then store that data in a variable with ob_get_content()
. But I'd also need to run the function after the rest of the page displays.
Here's some code I have tried without success (this is the content area inside the body tag):
<div id='part1'>
<p>here is part 1 of the content</p>
</div>
<div id='part2'> // this is where the function output will be inserted after processing it
<p>part 2</p>
<?php echo long_function();?>
</div>
<div id='part3'>
<p>this is part 3 of the content
</div>
<?php
function long_function() {
// some process that takes a long time to get data
// and stores it in the $part2_content
return $part2_content;
}
The result should be that the part1 and part3 div content should be displayed. And then, when the long_function()
finishes with gathering up it's data, that data should be output in the 'part2' section.
I've tried to put an ob_start()
at the beginning of long_function()
, then $part2_content = ob_get_contents()
to store that output data (without an ob_flush).
I think that I may need to add some sort of DOM 'write' to the 'part2' ID, but not sure of the right combination to accomplish.
CodePudding user response:
I believe you can't do the server side rendering. php is back-end language, that run the hole script file, then last thin print the output
for example: in a function: you cant return then call code after
function sayHi(){
$word = 'hi';
return "bye";
echo $word; // this code will never work :)
}
sloution ?
so you need to use Clint side rendering
for example use ajax
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script.
CodePudding user response:
Based on this answer which is completely acceptable: https://stackoverflow.com/a/46871956/17292588
PHP is a server-side programming language. It gets executed when you request a page. So you cannot execute it after the page has been loaded. If you need to check if something has loaded on the client side, you'll have to use a client-side programming language like JavaScript.
I suggest you to putting this long_function
in a another route and request it with Ajax during (or after) loading page.