Lucas
Lucas

Reputation: 3715

Live ajax content loading

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?

Upvotes: 1

Views: 408

Answers (2)

Ron van der Heijden
Ron van der Heijden

Reputation: 15070

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';

Upvotes: 1

user1636522
user1636522

Reputation:

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.

Upvotes: 0

Related Questions