I want to fetch data from database and show the result in codeigniter view with delay.
My code looks like this :
function loadPage($data) {
for($i = 0; $i < count($data); $i++) {
$this->load->view('mypage', $data[$i]);
sleep(5);
}
}
But this only load page once and show all data. What I need is load page with $data[0]
, delay 5 secs, load page with $data[1]
, and so on.
Please advice. Thank You.
Edit :
I want to do this with php. Not javascript or jquery.
PHP processes in the server and returns the processed html to the browser. That's how it works. But as you have explained in the comments, I think what you wanted to do is display the content to the browser while the for loop is running.
To do that you need to use output buffering (AFAIK, CI already calls ob_* methods in the core) so it might cause problems (or may not work as you would expect.) However, instead of loading the view multiple times, I suggest you to pass the data to the view and loop it there (and display the result one by one with a sleep.)
You can do it this way.
in your controller:
public function index(){
$data = [1,2,3,4,5];
$this->load->view('mypage', ['data' => $data]);
}
In your view (mypage.php):
<?php
while (@ob_end_flush());
ob_implicit_flush(true);
for($i = 0; $i < count($data); $i++) {
echo $data[$i];
sleep(3);
}
?>
Hope it helps :)
Send the $data
array to the view file as we cannot return from the view file back to the controller to execute the next line of code all the time.
Thus the code needs to be placed in the view file itself.
let $data
be the array.
<?php
foreach($data as $row) {
?>
//use `$row` where you want to use in the HTML section of the view file
<?php
sleep(5);
}
?>
NOTE : One basic question after reading your code You are calling view file from the controller function that's absolutely right. But once the call is made and you are in view file are you calling the controller function to execute the next part of for loop?
Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view.