0

I am making a jQuery Ajax form submit to a PHP page that I want to return values dynamically instead of all at once. For example, if my jQuery code is:

jQuery.ajax({
      type: "POST",
      url: "$PathToActions/Accounts.php",
      dataType: "html",
      data: "action=register&accounts=" + accounts,
      success: function(response){
           alert(response);
      });

My Accounts.php looks something like:

     <?php for ($i = 0; $i < 10; $i++) {
        echo $i;
        sleep(2);
     } ?>

My code outputs 012345679 right now in a single JavaScript alert after a ~10 second delay. Is it possible to get it to output the values as soon as they are generated instead of all at once?

Thank you!

5
  • 1
    You can't do that ... the output only sent after php finish running Commented Aug 10, 2010 at 4:43
  • @Bang Dao - well, how would something like a shoutbox/chat room made in Ajax work? I believe it would be the same approach.. Commented Aug 10, 2010 at 4:55
  • they use other way. I will pass as an answer Commented Aug 10, 2010 at 4:59
  • There is no such approach. Ajax chat just makes separate ajax requests every N seconds retreiving new data from server. Commented Aug 10, 2010 at 4:59
  • @Bang and @ehpc. Hmm I see. What approach do they use? Are they querying a database or so every few seconds? Commented Aug 10, 2010 at 5:02

2 Answers 2

2
key = something_identify_here; //I use global variable for easier to understand

setInterval(function()
{
    jQuery.ajax({
      type: "POST",
      url: "$PathToActions/Accounts.php",
      dataType: "html",
      data: "action=register&accounts=" + accounts + '&key=' + key,
      success: function(response){
           alert(response);
           //change the key if its need
      });
}, 2000); //do query foreach 2 second

And on the php file, we code something like this

showContentByKey($_GET['key']);

The main idea here is: you do a ajax query for each 2 second and display the returned data. On your server, the php script send some data (maybe difference from each time) when requested.

Sign up to request clarification or add additional context in comments.

Comments

-1

yes you can do it through ob_start.

<?php 
ob_start();
for ($i = 0; $i < 10; $i++) {
        echo $i;
        sleep(2);
        ob_flush();
        flush();
     } 

ob_end_clean(); 
?>

2 Comments

It doesn't serve the purpose. Yes, it works if I visit the PHP page directly but it still returns the value to the AJAX form with 10 second delay and returns its all at once.
@Aamir sorry flushing output outside the loop. now the code is corrected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.