Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

There are some good answers already, but none of them are really 100% reliable or cross-browser. A safer approach would probably be to chunk your response into "pages". Each request can specify something equivalent to a LIMIT and OFFSET and you keep making requests until you get an empty response. That incurs some extra overhead on both the client and server, but it would be more robust.

Solution 3:

Taken from: https://stackoverflow.com/questions/287286/jquery-is-req-readystate- 3-possible

Assign your ajax call to a variable and attach an event to its readystatechanged.

var xhr = $.ajax(...);

xhr._onreadystatechange = xhr.onreadystatechange;

xhr.onreadystatechange = function() {
    xhr._onreadystatechange();
    if (xhr.readyState == 3) alert('Interactive');
};

Solution 4:

I don't know for sure if this will work but it's worth a try:

$.ajax({
  statusCode: {
    206: function() { // 206 is partial content// do work
    }
  }
});

Solution 5:

Can you use long polling (comet) instead of ajax? Then you can flush the output buffers and read the content as the request is being processed.

http://www.zeitoun.net/articles/comet_and_php/start

Post a Comment for "Is It Possible For An Ajax Request To Be Read Before The Response Is Complete?"