1

How can I dynamically parse a content that was returned by the php file that ajax sends request to?

My code:

jQuery(function () {
    var request = jQuery.ajax({
        url: "ajax/db.php",
        type: "POST",
        data: {
            addresses: '<?php echo implode(' * ', $addresses); ?>'
        }
    });
    request.done(function (msg) {
        jQuery("#response").append(msg);
    });
    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
});

ajax/db.php

<?php

    echo 'hello';
    sleep (5);
    echo 'world';

What I want to achieve is displaying the ajax/db.php file response dynamically - first append the hello string into the #response object and after 5 seconds of sleep it should append another piece of string - world.

At the moment the code just appends the whole output after 5 seconds.

Is there anyway to make it work like a live-response?

Ron van der Heijden
  • 14,803
  • 7
  • 58
  • 82
Lucas
  • 3,517
  • 13
  • 46
  • 75
  • Use `setTimeout` on the clientside. – mishik Aug 29 '13 at 15:14
  • Use two separate AJAX requests, and two different PHP files. You're trying to implement what's called [long polling](http://stackoverflow.com/questions/333664/simple-long-polling-example-code), and it's a bit more complicated. – Blazemonger Aug 29 '13 at 15:16

2 Answers2

1

This is how a PHP server works. 1 request, 1 output.

If you want to send the data before and after the sleep() you could use ob_flush()?

Something like this (sorry long time ago I used this, so don't shoot if not working)

<?php

    echo 'hello';
    ob_flush();
    flush();
    sleep (5);
    echo 'world';
Ron van der Heijden
  • 14,803
  • 7
  • 58
  • 82
0

sleep(5) stops PHP execution, so nothing is returned back to the browser until execution terminates. Javascript has to wait 5 seconds more to get back the entire response, that's it. If you want to split the response into multiple parts you'll have to make two Ajax requests successively.