Sinmok
Sinmok

Reputation: 656

Hook additional data before $.post() on all calls

I'm having trouble figuring out how to hook in data each time jQuerys $.post() method is called.

I have several event handlers that obtains values from throughout the page before submitting them to the server via AJAX. An example of such a call is as follows:

var data = {
    link_data:{'foo': 'bar', 'foo2' : 'bar2'}
};

$.post('some_url',data,function(returned_data){
    //Do something with returned_data
});

However, I was wondering if there was a way of hooking in an additional piece of data that is sent with every $.post() request made.

Essentially, what I was hoping for was a way to amend the 'data' parameter that's sent to the server just before submission so that the sent value looks something more like this:

{
 token: some_predefined_variable,
 link_data{'foo': 'bar', 'foo2' : 'bar2'}
}

Is there a way to hook this in so that I don't have to go and amend every single method where data is being sent to the server by $.post()?

Thanks.

Update: I found the best solution was actually posted here. Bit annoying that you have to manually set the post data but it works :)

Upvotes: 0

Views: 118

Answers (4)

Musa
Musa

Reputation: 97672

You can use $.ajaxSetup() and beforeSend

$.ajaxSetup({
    beforeSend: function(jqXHR, settings){
        settings.data = {token: some_predefined_variable, link_data : settings.data };
    }
});

Upvotes: 3

AdityaParab
AdityaParab

Reputation: 7100

You might wanna implement your own function, like

function SinmoksPost(userData){
    var x = {
        token: some_predefined_variable,
        data:userData
    }

    $.post('some_url',x,function(returned_data){
        //Do something with returned_data
    });
}

and then call SinmoksPost instead of $.post

Upvotes: 1

adeneo
adeneo

Reputation: 318182

You can do this with $.ajaxSetup() :

$.ajaxSetup({
    data: {link_data : {'foo': 'bar', 'foo2' : 'bar2'} }
});

See this link for a better explanation to how it's done (the above is really all you need).

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

you can try this:

var data = {
    link_data:{'foo': 'bar', 'foo2' : 'bar2'}
};

data.token = some_predefined_variable;

Upvotes: 1

Related Questions