Search code examples
jqueryajaxresponse

After a $.ajax request, is there any way to get the request's params from the response?


If I make a jQuery AJAX call:

 $.ajax({url: 'example.com', data: {bar: 2}).done(handleResponse);

is there any way I can get the parameters I passed to the AJAX request (ie. the data option) from inside the response handler? In other words I'd like to be able to do:

handleResponse = function(response) {
     var requestData = response.something.something.data;
     // requestData.bar == 2
}

And just to be clear, I know I can do it by using a "partial" from a library like underscore, ie.:

 var data = {bar: 2};
 $.ajax({url: 'example.com', data: data).done(_(handleResponse).partial(data));

handleResponse = function(data, response) {...

but I was just wondering if there was any other (cleaner) way to do it using the arguments jQuery passes to the response handler.


Solution

  • I don't quite understand the rest of your code, but given the first part:

    $.ajax({url: 'example.com', data: {bar: 2}).done(handleResponse);
    

    you can access the data in the handler:

    handleResponse = function(response) {
         var requestData = this.data;
         // requestData.bar == 2
    }
    

    this contains the options passed to $.ajax unless you also passed a context option.