0

I created a CometServlet according to this example http://tomcat.apache.org/tomcat-7.0-doc/aio.html. Then I tried to get data from it using JQuery. The code is following:

$(function() {

        $.longPoll = function(url, success, error) {
        $.ajax({
            url : url,
            success: function(data, status) {
                $.longPoll(url, success, error);
                if (success) {
                    success(data, status);
                }
            },
            error: function(data, status) {
                $.longPoll(url, success, error);
                if (error) {
                    error(data, status);
                }
            }
        });

    };

    $.longPoll("./comet", "", function(data, status) {
        alert("success:" + data);
    }, function(data, status) {
        alert("error:" + data);
    });
});

The problem is that the success function doesn't trigger (even though I can see in the FireBug console that the data comes). I think it happens because the server doesn't close a response writer, but it is a goal of the long-polling :)

Does any one have any ideas how it can be solved?

Pavel
  • 969
  • 2
  • 9
  • 19

2 Answers2

1

You need to overwrite the xhr onreadystatechange in order to check for readyState === 3 with jQuery .ajax(). Example:

var xhr = $.ajax({});
xhr._onreadystatechange = xhr.onreadystatechange;  // save original handler

xhr.onreadystatechange = function() {
     xhr._onreadystatechange();         // execute original handler
     if (xhr.readyState === 3) alert('Interactive');
};
jAndy
  • 212,463
  • 51
  • 293
  • 348
  • Thanks for your answer! I added: beforeSend : function(xhr) { xhr._onreadystatechange = xhr.onreadystatechange; xhr.onreadystatechange = function() { if (xhr.readyState === 3) { alert(this.responseText); } else { xhr._onreadystatechange(); } }; xhr.onprogress = xhr.onreadystatechange; } to my $.ajax() request, but nothing changed. Sorry, I can't format the code. – Pavel Aug 31 '10 at 14:29
0

The problem solution is to add timer for checking the long-poll stream for a new data. Great explanation is here: http://www.bennadel.com/blog/1976-Long-Polling-Experiment-With-jQuery-And-ColdFusion.htm

Thanks everyone.

Pavel
  • 969
  • 2
  • 9
  • 19