PDA

View Full Version : Manage all the Ajax requests in the same way



American horizon
30 May 2016, 12:36 AM
Hi, i need to perform some ajax requests and, once the response is retrieved, i want to send it to the main controller that shows a window with message retrieved from the server.

Actually i manage it in the "success" and "failure" parameters of the request method in EACH ajax call, but this cause a redundant code.
Since i need to manage alla ajax response in the same manners, i want to create a "default" action for all ajax requests, that automatically redirects every response to the controller. How i can do that?

alexander.urban
30 May 2016, 9:10 AM
I have made an Ext.Ajax.requestAuthn function that wraps around the original Ext.Ajax.request function. You could do similar:


Ext.Ajax.requestAuthn = function(options) {
var success = options.success,
callback = options.callback,
error = options.error;
if(Ext.isFunction(success)) options.success = function(response) { if(isLoggedIn(response)) success(response); }
if(Ext.isFunction(callback)) options.callback = function(response) { if(isLoggedIn(response)) callback(response); }
if(Ext.isFunction(error)) options.error = function(response) { if(isLoggedIn(response)) error(response); }
Ext.Ajax.request(options);
}

American horizon
31 May 2016, 12:52 AM
Hum. Can you write an example of how you use it?

alexander.urban
31 May 2016, 1:51 AM
You use it the same way you would use Ext.Ajax.request. What my wrapper function does is add a call to a function (isLoggedIn) to all callbacks.

When I made it, I already had like 200 calls to Ext.Ajax.request in my source code.

What I did was search and replace all Ext.Ajax.request calls to Ext.Ajax.requestAuthn, and everything worked the same as before, just with the little call to the isLoggedIn function after every Ext.Ajax.request, in which I check whether the response indicates that the user is no longer logged in and triggers a reauthentication if he isn't.

American horizon
31 May 2016, 5:45 AM
Can i save it in a standalone js file? And if yes, how i can include it inside another file, for example a controller, in order to use it?