0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hello, thank you! Your answer sent me in the right direction. +1
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.