Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an ajax (jquery) request response progressively without waiting for it to finish?

I want to make a form that will use jquery to submit a list of keyword to a php file, this file could take a lot of time to load depending on the size of the keywords list.

What I want to do is to load the php response into a div or container in real time without using iframes.

All the ajax request I know have to wait until the request has finished before having access to the response, I need to get access to that response even when it hasn't finished so I can update the progress in real time.

like image 508
Sebastian Avatar asked May 02 '10 15:05

Sebastian


3 Answers

Indeed there is a way. With plain old xmlhttpobjects I monitored the readyState. Ready state 4 means the request has ended. Ready state 3 means I can get some of the output and wait for more:

request.onreadystatechange=function()
{
    switch(request.readyState)
    {
        case 4:
            console.log("all good things come to an end");
        break;
        case 3:
            console.log("o, hai!" + request.responseText);
        break;
    }
}

I believe you can achieve the same using jQuery: jQuery: Is req.readyState == 3 possible?

like image 129
nc3b Avatar answered Oct 04 '22 18:10

nc3b


Recently Josh has posted about COMET technology, which seems to be right for you. There are couple of interesting links with examples in php.

How do I show the print with AJAX/jQuery?

like image 32
Nikita Rybak Avatar answered Oct 04 '22 17:10

Nikita Rybak


Updated: The most reliable way to use Ajax is to consider each Ajax request as being atomic: it works or it doesn't.

And you (the JS running on the page) don't really get any feedback as your request is executing. So you'll need multiple calls. But be careful! Lots of overhead per call and most browsers will only execute one or maybe two at a time.

I suggest using a busy indicator to the human. You could also show a count down clock that updates at least twice per second to make it seem like something is happening.

Added:

You may also want to re-architect your solution. Eg view the update process as a batch job that the Ajax kicks off by submitting the request. Then make further Ajax calls to learn (and then) display the progress of the batch job to the human.

Comet and other "keep the pipe open strategies" can be used but are tough to get working reliably and tend to use a lot of resources. A more pedestrian polling technique can be a lot easier to get going. Then optimize if needed.

like image 29
Larry K Avatar answered Oct 04 '22 17:10

Larry K