Search code examples
javascriptphpjqueryajaxlong-polling

Why the jQuery's ajax ".always" functions is not working properly


I have following Javascript code which always ask server for some data.

;var EVENTS = {};
;(function($) {

    EVENTS.Test = {
      getEventsData: function() {

        var events_request = $.ajax({
            url: "test1.php",
            contentType: 'application/json-rpc',
            type: "GET",
            timeout: 30000
        });

        events_request.done(function(results) {alert(results);});

        events_request.fail(function(results) {alert(results);});

        events_request.always(this.getEventsData);
    }   
    };

})(jQuery);

EVENTS.Test.getEventsData();

Server side php is as following

<?php
sleep(5); 
echo "This is response";
?>

What I want to do is get the data from server in case either ".done or .fail" finish, so I use ".always" function. But only two request is made to the server, after that no request is made. I used Firebug to debug.But unfortunately no any error. How can I know why the ajax is not working after two request. How to make it working?

Thanks in advance.


Solution

  • The problem is when the getEventsData method is invoked by ajax callback this does not refer to the Test object so this.getEventsData will be undefined. The solution is to use Function.bind() or $.proxy() to pass a custom execution context to the callback

    events_request.always($.proxy(this.getEventsData, this));
    

    Another option is to set the context option of $.ajax() so that all the callbacks will get a custom execution context.

    This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).