views:

290

answers:

1

In the web app I am working on there is potential for very long running ajax queries.

I'm using jQuery's $.ajax method to do something like:

this._xhr = jQuery.ajax({
    type: "GET",
    url: "/path/to/service",
    data: "name=value",
    success: function(data, message){
        // handle a success
    },
    dataType: "json"
});

Is there a way to modify the success callback after this._xhr.readyState = 2 (loaded) and before this._xhr.readyState = 4 (completed)

I tried modifying this._xhr.onreadystatechange but found that jQuery does not define onreadystatechange.

A: 

The abort method sounds like the best option to me.

I don't know much about the ajax method internals, but I can think of a few ways to do what you want. Both involve global state and would break if it's possible for your user to send a second request before the first has finished, so I'm not sure I recommend them.

First, you could keep a reference to the method that does your success work, and change it:

MySuccessMethod = function(d, m) { /* handle a success */ };

this._xhr = jQuery.ajax({
    type: "GET",
    url: "/path/to/service",
    data: "name=value",
    success: function(data, message){ MySuccessMethod(data, message); },
    dataType: "json"
});


// later...
// user cancels request, so change the success method
MySuccessMethod = function(d, m) { /*print a simple message*/ }

Alternatively, you could just put all the logic in the one success method, and use a global flag to determine what to do:

success: function(data, message){
    if (RequestHasBeenCancelled) {
        //display a simple message
    }
    else {
        // handle a success
    }
},
Gabe Moothart
Thanks, I've gone ahead and used `abort` for now, but I like the thinking in your first suggestion, I could take that idea and apply something similar to my code and actually without involving global state. Thanks Again.
andrewwatts