Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for an AJAX request to be read before the response is complete?

I have an ajax request that takes a while to complete, but the server does output some content along the way. If I load the request simply in the browser, I can see the page slowly loading and it can be stopped at any time. Is it possible to access an incomplete ajax request before the server closes the response?

like image 940
hughes Avatar asked Jul 13 '11 17:07

hughes


1 Answers

The way to accomplish this is by listening on the readyState in the the xhr object. When readyState == 3 it means new content has arrived and you can access it. The technique is referred to as Comet.

Note however that different browsers behave differently here, IE will not allow you to access it See Here and webkit browsers (Chrome/Safari) buffer 2KB of data before making it available. After accounting for that though, you can then listen for the change then act on it.

Unfortunately, jQuery does not currently support this out of the box. You can get around this as noted in Bug #8327, where they basically fall back to polling on the readyState to see if it changes. They have plans to maybe do something about it in the future, Bug #9883, but don't hold your breath.

So finally, yes it is possible, no it is not easy.

like image 100
Andrew Avatar answered Sep 19 '22 15:09

Andrew