2

So i have the below code to add the additional data to any ajax request made by my app, but the problem is it's working only first time when the page loads , as the application is single page ajax based application , i want to use the updated variable value inside ajaxSetup to make sure all the things work as expected but somehow it takes the old value , i know ajaxSetup setups the data for ajax call on page load. here is what my ajaxSetup looks alike:

var token = 'b62e0352ae559ae1d1e98f0d26604630'; // this variable updates every minute.
setInterval({
 var token = $('meta[name=token]').attr('content'); // the updates the token variable every 1 minute
},1000*60*1);
$.ajaxSetup({
    data: {
        token: token
    }
});

as there is predefined token, after every minute it does update , and i just want to pick the updated value of meta tag and then use it for any ajax request made on page. if there is any another way or correction of this code it will be very helpful.

7
  • 1
    Why not request the token when needed? like data:{ token:function(){ return $('meta[name=token]').attr('content'); }} Commented Nov 27, 2015 at 14:41
  • @sofl data is not only token , it has many other keys inside it. so need to update multiple ajax requests with in addition the token value Commented Nov 27, 2015 at 14:42
  • 1
    You can still add more keys. data:{ token:function(){...}, key1:'a',....., I don't see any problem here. Commented Nov 27, 2015 at 14:46
  • @sofl post it as answer i will accept it. your method worked :) Commented Nov 27, 2015 at 14:46
  • @sofl post it as answer, i will accept your answer Commented Nov 27, 2015 at 14:46

1 Answer 1

2

Request the token when needed so it will be up to date each time.

$.ajaxSetup({
    data: {
        token: function(){
            return $('meta[name=token]').attr('content');
        }
    }
});
Sign up to request clarification or add additional context in comments.

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.