You should take a look at the dataFilter property of $.ajax . This property accepts a function that runs immediately after receiving the request, but before any handlers are executed. The main purpose of this is to pre-process the data obtained before it was processed by jQuery itself. Therefore, you will receive raw data. You can perform intermediate processes there, for example, your login.
To fix this configuration to all ajax calls, we use $.ajaxSetup to predefine dataFilter for all ajax requests. Therefore, each ajax request will be executed by the dataFilter handler before executing the local handlers.
Regarding the sample code, here is a demo that pretty much works as expected :
function login() { console.log('login initiated: you are not logged in'); } $.ajaxSetup({ dataFilter: function (origdata, type) { //the type is determined by the type you indicated in the ajax call //if not json, we return the data unharmed if (type !== 'json') return origdata; //data filter receives the raw response. since we have determined it json //we parse it using jQuery parseJSON to check the contents var data = $.parseJSON(origdata); if (data.auth) { //if logged in, we just return the data return origdata; } else { //otherwise, we execute the login //since returning something is required, we return false so local handler //data checks will fail against the false data login(); return false; } } }); //the url and data passed is for jsFiddle to work. //logged in $.post('/echo/json/', { json: JSON.stringify({ auth: true }) }, function (data) { //in our handler, it your normal "check data before use" //if data is truthy, it skips this check and moves on if(!data) return; console.log('data retrieved successfully', data); }, 'json'); //not logged in $.post('/echo/json/', { json: JSON.stringify({ auth: false }) }, function (data) { //since we returned false, the code stops at this check if (!data) return; console.log('you should not see this since data is false, per dataFilter return', data); }, 'json');
Joseph
source share