Reputation: 8098
I have to pass an additional token value to the website so that I can validate the request.
The function that adds the value is this:
AddPageTokenToAjaxRequest = function (data)
{
data.hfPageToken = $('#hfPageToken').val();
return data;
};
, and it would have to be used like this:
function asociate(id)
{
$.ajax({
url: postbackURL,
type: 'POST',
data: AddPageTokenToAjaxRequest( { id: id} ),
success: function (result)
{
refresh();
}
});
}
The thing is that I do not want to change the code in about 100 of these calls. Is there a way to override the data sending ajax call so that I do not have to make 100 changes?
Upvotes: 0
Views: 1921
Reputation: 8098
After seeing Polymorphix's answer I did another search and I found this piece of code here: https://stackoverflow.com/a/12116344/249895
$(document).ready(function ()
{
var securityToken = $('#hfPageToken').val()
$('body').bind('ajaxSend', function (elm, xhr, s)
{
if (s.hasContent && securityToken)
{ // handle all verbs with content
var tokenParam = "hfPageToken=" + encodeURIComponent(securityToken);
s.data = s.data ? [s.data, tokenParam].join("&") : tokenParam;
// ensure Content-Type header is present!
if (s.contentType !== false || options.contentType)
{
xhr.setRequestHeader("Content-Type", s.contentType);
}
}
});
});
I tested this and it works just fine.
Upvotes: 0
Reputation: 1075
Could you use jQuery.ajaxSend() to modify your data before sending?
Whenever an Ajax request is about to be sent, jQuery triggers the ajaxSend event. Any and all handlers that have been registered with the .ajaxSend() method are executed at this time.
something like (pseudo code):
var modify = function(event, jqXHR, ajaxOptions)
{
ajaxOptions.data = AddPageTokenToAjaxRequest( { id: ajaxOptions.data} )
}
$.ajaxSend(modify(e, jqXHR, opts));
Just a thought. Seems like it might work.
Upvotes: 1