I have a for loop in PHP and an Ajax call in JavaScript with Jquery library. My problem is that i want to update the page after each php loop. Now its waiting 10 seconds and after that, shows me the page. I want to display in real time line after line.
data.php
<?php
for($i=0;$i<10;$i++) {
echo "lorem ipsum" . "<br>";
sleep(1);
}
?>
And the index.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function ajaxCall(){
$.ajax({url:"data.php",success:function(result){
$("#div1").html(result);
}});
}
setTimeout(ajaxCall(), 1000);
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
In your data.php, there is no need for sleep and for loop. The loop will be done in Javascript (with setTimeout).
So data.php can look something like:
<?php
echo "lorem ipsum" . "<br>";
?>
And your index.php should append the data:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function ajaxCall(){
$.ajax({url:"data.php",success:function(result){
$("#div1").append(result);
}});
}
setTimeout(ajaxCall, 1000);
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
You essentially want to perform 10 page updates, each after one second based on each iteration of your loop on the server side php code. I suggest you redesign so that the looping occurs on the client side, and on the server side you simply respond to each request. I think this approach is easy to understand.
The below client side code is not tested and shows the approach (index.php)
//this is called 10 times, with i being the number of the call starting at 1
function ajaxCall(i){
//note the query string parameter being passed to the php script
$.ajax({url:"data.php?i="+i,success:function(result){
$("#div1").html(result);
if(i<10){ //if we have not reached 10 calls, delay and then call again while incrementing the count
setTimeout(ajaxCall(i+1), 1000);
}
}
});
//make the first ajax call
setTimeout(ajaxCall(1), 1000);
In data.php you need to check that query string parameter. Note there is no loop and no sleeping in your server side code any more.
<?php
$i = $_GET["i"];
//do something with $i which should be in the range 1-10 (you should check this)
echo "lorem ipsum " . $i . "<br>";
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.