-1

let's say I have a dummy server side code (ajax_response.php) which looks like this:

<?php

for ($i = 1; $i <= 10; $i++) {
    echo $i;
    sleep(1);
}

?>

which means after 10 secs it will echo '12345678910'.

I also have the following jquery code:

$.ajax({
        type: 'POST',
        url: 'ajax_response.php'
    }).then(function(results) { 
        //... success

    }, function {
        //... execute if error occurs
} );

I can use the above ajax to get the response from ajax_response.php, but the problem is, the success function (ie. the first function inside .then) will only be called when ajax_response.php finished executing (which takes 10 secs).

I would like to know if I can make this more efficient. ie. as soon as echo is called in the php file, I'll immediately get the response from the client side.

It will be great if you can include some sample code.

Josh
  • 692
  • 2
  • 9
  • 38
  • No you can't! Websockets or comet seems to be more what you're looking for ? – adeneo Oct 29 '13 at 18:13
  • Or http://stackoverflow.com/questions/333664/simple-long-polling-example-code – mplungjan Oct 29 '13 at 18:14
  • do you want something like a progress bar with ajax? a simple (but somewhat dirty) solution is to let php write to a file, and poll the file through ajax (and a different php script) with an interval – x4rf41 Oct 29 '13 at 18:14
  • If you instead posted to an iframe, you could output javascript to the iframe that modifies the parent page, assuming the content is being sent to the browser each time you echo (not sure if php does it automatically, in cfml you have to tell it to do that, and there are minimum content requirements you have to meet for some browsers to read it). – Kevin B Oct 29 '13 at 18:24

1 Answers1

0

In javascript side

   var interval;
   $.ajax({
        beforeSend: function(){
            interval = setInterval(function(){
                    $.get("http://example.com/pr.txt").done(function(progress){
                        console.log(progress)
                    })
                },10);
        },
        type: "POST",
        url: "http://example.com/req.php",
        data: reqdata,
        cache: false,
        success: function(html) {
            clearInterval(interval);
            var values = html.split('[mydata]');
            var mydata = values[1];
        }
   });

`

In PHP side

unlink("progress.txt");
while ($i <= 20) {
    writeToFile(progress, "Mail sent to $i <br>");
    sleep(4);
    $i++;
}
$final = array('status'=>'ok', 'numbers'=>$success_numbers);
echo json_encode($final);

`

donztobs
  • 1
  • 1