I am trying to get token from api and wanted to send each ajax call in jquery.
function fetchToken(){
// duplicate backend call by `delay` returns a promise
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('test');
}, 500);
});
}
function interceptAjaxCall(){
var ajaxReference = $.ajax;
$.ajax = function (options) {
fetchToken()
.then(function (tokenfrombackend) {
console.log(tokenfrombackend);
var success = options.success;
options.headers = { 'token':tokenfrombackend}; //this does not set token in each ajax call header!
options.success = function (data, textStatus, jqXHR) {
if (success)
success(data, textStatus, jqXHR);
};
//return ajaxReference .apply($, arguments); /*returning here fails ajax call*/
})
return ajaxReference.apply($, arguments);
}
Intercepting each ajax is working but does not set token in each ajax header even after getting token value. Thanks in advance