Aamir Mansoor
Aamir Mansoor

Reputation: 3

jQuery AJAX - Return dynamic content

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!

Upvotes: 0

Views: 1163

Answers (2)

Adeel
Adeel

Reputation: 19238

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(); 
?>

Upvotes: -1

Bang Dao
Bang Dao

Reputation: 5112

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.

Upvotes: 2

Related Questions