user1848605
user1848605

Reputation: 747

Can I change jQuery.ajax's function call arguments (sent in data) through beforeSend event?

I have a code that goes something like this:

var offset = 1;
$.ajax({
    url: /www/loadmoredata,
    type: 'POST',
    data: {
        limit: 1,
        offset: offset
    },
    beforeSend: function (xhr, ajaxOptions, thrownError) {
        offset++;
    }
}); 

Now I would expect the offset passed through ajax to be 2, since I increment in beforeSend, which runs before the AJAX is processed. However, it seems that beforeSend increments the offset variable AFTER it has been appended as data to the function call.

My question is: am I doing something wrong or is this not what beforeSend method is meant to be used for? And if it isn't, what would be the right way to do what I intended?

Upvotes: 1

Views: 605

Answers (1)

Sam
Sam

Reputation: 2201

Correction, by the time beforeSend is called, the Request has already been constructed and the data object you are trying to change has been put into the Request. Here is the documentation for beforeSend http://api.jquery.com/jQuery.ajax/ . The ajaxOptions parameter are not the options for the current ajax request. So you will be able to change the data you are passing into the request.

Maybe if you give us a higher level idea what you are trying to achieve we can help?

-- Original Suggestion --

Offset is still in scope, but your expectations are incorrect. Give this a try:

var offset = 1;
$.ajax({
    url: /www/loadmoredata,
    type: 'POST',
    data: {
        limit: 1,
        offset: offset
    },
    beforeSend: function (xhr, ajaxOptions, thrownError) {
        ajaxOptions.data.offset += ajaxOptions.data.offset;
    }
});

Upvotes: 3

Related Questions