bob jomes
bob jomes

Reputation: 281

Show each result one by one

I have a code which increases a URL parameter in a while loop until $i is equal to 10. When this happens, it will display each number up to 10 (as this is when $i stops increasing) - in this case it would be 1, 2, 3, 4, 5, 6, 7, 8, 9.

The problem with this is that only when $i is equal to 10 does it show 1, 2, 3, 4, 5, 6, 7, 8, 9 - I need it to display the numbers as it happens (rather than waiting for $i to equal 10!).

<div id="here"></div>

<script>
$(document).ready(function(){
        $.ajax({
            type: "POST",
            url: "test2.php",
            success: function(data) { $("#here").html(data);  }
        });
});
</script>

test2.php:

while($content = file_get_contents('https://www.example.com?id='.$i)) {
   if($i !== 10) {
      echo $i;
   }else{
      break;
   }
   $i++;
}

Upvotes: 5

Views: 155

Answers (3)

Akshay
Akshay

Reputation: 2229

I really think async would help you here. Could you maybe try this code ?

<script>
$(document).ready(function(){
        $.ajax({
            type: "POST",
            url: "test2.php",
            async: false,
            success: function(data) { $("#here").html(data);  }
        });
});
</script>

Upvotes: 0

guest271314
guest271314

Reputation: 1

You can alternatively request each file in sequential order using .queue(), .append()

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

$({}).queue("ajax", $.map(arr, function(item, i) {
  return function(next) {
    return $.ajax({
              type: "POST",
              url: "test2.php",
              data: {n:item}
           })
           .then(function(data) { 
             $("#here").append(data);  
             next();
           });

  }
})).dequeue("ajax")

php

if (isset($_POST["n"])) {
  $content = file_get_contents("https://www.example.com?id=" . $_POST["n"]);
  echo $content
}

Upvotes: 1

Ben Shoval
Ben Shoval

Reputation: 1750

There is no stable way to have a PHP script generate output until the script ends.

If you need a countdown, you can put the while loop in your Javascript and have it call the PHP script with something like:

test2.php?i=1

then

test2.php?i=2

etc.

Upvotes: 0

Related Questions