Ext.Ajax: Creating global listeners
I started developing an application using ExtJs (of course) and at some point, after writing thousands of lines of code, having hundreds of ajax calls, it occurred to me that I want to perform an action against every ajax call.
So, the requirements were:
1. If user action has initiated an Ajax call but user session is expired (server returns 401 in this case), UI should show an alert. On this alert when user click on “OK” it should redirect user to login page.
2. It must also suppress any defined ‘failure’ handler for the corresponding ajax call.
Changing all ajax calls and adding appropriate conditions to ‘failure’ functions was going to be a tedious job. I came across a way to add global listeners which will be applicable for all ajax calls made through the application. I was having a js file which was being included in all views, so I added following code in that file:
Ext.Ajax.on('requestexception', function (conn, response, options) { if (response.status === 401) { Ext.Msg.alert( "Login session expired", "Your log-in session has expired", function(btn, text){ window.location = '/login'; } ); } return false; }); |
This solved (1) above but the ‘failure’ defined for the ajax call was also getting executed. I found no way to purge those listeners (I tried purgeListeners() and abort()). With some further investigation I found a way to redefine the ‘failure’ function. So, the code looked like:
Ext.Ajax.on('requestexception', function (conn, response, options) { if (response.status === 401){ options.failure = function(){/*do nothing*/}; Ext.Msg.alert( "Login session expired", "Your log-in session has expired.", function(btn, text){ window.location = '/login'; } ); } return false; }); |
This solved (2) above.
So far I am happy with this solution. Why? Because it solved the purpose
Hope it will be helpful for you if you got stuck in similar scenario.
Ref. http://docs.sencha.com/ext-js/3-4/#!/api/Ext.Ajax-event-requestexception

