简体   繁体   中英

print one by one itreation of loop instead of at once using php and ajax

I m trying to print out loop iteration one by one instead of one using ajax is this possible? Like iteration 1 iteration 2

etc but they should not at once but one by one as the loop work

Here is my ajax and php code.At this moment the whole code process and finally gives output instead of one by one

<div id="div1"></div>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>

jQuery(document).ready(function($) {

$("button").click(function(){

  $.ajax({url:"counter.php",success:function(result){
    $("#div1").html(result);
  }});
});


});
</script>
<button name="button" value="button" style="width:200px; height:200px;">

Here is PHP code

<?php

     for ($i = 0; $i < 10; $i++)
     {
       echo "<div>" . time() . ": Iteration $i</div>";
       sleep(1);

       flush();
     } 

    ?>

It's due to once you post a request loop get the response and revert the response to ajax method loop execute so fast , you need to sleep the loop once it execute so time, so that once you got a result after some second again loop execute and you got again a response

please follow this timeout function to sleep loop for a while

Where i belong the param you pass throughout the loop and not lost the dynamic value....

> (function(i){
>         setTimeout(function(){
> 
> }, 1000 * i);
>     }(i));

That's true. PHP will (by default) send the output if the full PHP script is executed. If you want a counter you should loop through the AJAX calls instead of your PHP code. This example will work:

    var currentCounter = 0;
    var countTill = 10;

    function invokeCounter()
    {
        $.ajax({url:"counter.php?counter="+currentCounter,success:function(result)
        {
            $("#div1").html(result);

            if(currentCounter >= countTill)
            {
                clearInterval(myCounter);
            }

            currentCounter++;

        }});
    }

    var myCounter = setInterval(function()
    {
        invokeCounter();
    }, 1000);

In your PHP you can get the current counter

<?php
    echo "<div>" . time() . ": Iteration ".$_GET['counter']."</div>";
?>

I think you know this isn't a right solution for a webcounter, but you are probably experimenting/testing something in JQuery/AJAX/PHP.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM