June 23, 2012

Intercepting and Routing AJAX calls with ExtJS

Hi there.
So yeah, I'm still messing around with ExtJS and still discovering it's quirky ways of making the lives of developers easier (to some extent, lets not get to optimistic now, shall we).
Today I want to share with you a nice way for intercepting and then routing AJAX calls from ExtJS. This may come extremely handy when you want to use relative paths within you Model/Store proxies, but want to test them for a specific server, meaning you want that relative URL to be converted into an absolute path. This way you don't introduce new code to the application but rather implement the solution externally (the HTML wrapper of the application is a nice option of doing it).
So say that our model looks like this (taken from Sencha docs):
Ext.define('User', {
extend: '',
fields: ['id', 'name', 'email'],

proxy: {
type: 'rest',
url : '/users'
Now, this Model will fetch data from a relative path to the web application it runs on, meaning that if you are running on http://localhost/myapp, it will go to http://localhost/myapp/users.
But this is not what we want. We want it to go to http://otherdomain/users. Enters the Ext.AJAX singleton.
By using the Ext.AJAX singleton we can intercept any AJAX call on the system and re-route it to a different location - here how it is done:
var URLPrefix = 'http://otherdomain/'
Ext.onReady( function() {       
Ext.Ajax.on("beforerequest", function(conn, options, eOpts){
options.url = URLPrefix + options.url
On the code above we're listening on the "beforerequest" event of the AJAX singleton, and the handler alters the URL by adding it a prefix of the desired domain.

That's it. Simple, ain't it?