views:

56

answers:

3

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?

A: 

Have you taken a look at this related Stack Overflow question?

Max
That doesn't seem terribly helpful to me - this question is much more specific, and the question you linked is also 2 years old. A lot has changed, including jQuery, since then.
Matt Ball
Fair enough. You're right that most of the info on comet + jquery is out of date. The Ape project still feels relevant.See this thread for more info: http://forum.jquery.com/topic/is-anyone-using-comet-reverse-ajax-with-jquery
Max
+1  A: 

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
Thanks for your answer!I added:<code>beforeSend : function(xhr) { xhr._onreadystatechange = xhr.onreadystatechange; xhr.onreadystatechange = function() { if (xhr.readyState === 3) { alert(this.responseText); } else { xhr._onreadystatechange(); } }; xhr.onprogress = xhr.onreadystatechange; }</code>to my $.ajax() request, but nothing changed. Sorry, I can't format the code.
Pavel
A: 

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