Passing Extra Data to an Ext AJAX Request Callback

By Jeff Denton Sep 16, 2008

I’m not ashamed to admin that I’ve fought with this problem for months. I’ve always put it on the back burner for a more convenient time, but today I just hammered away until I found a solution.

Now, to some of you (most???) this may seem trivially obvious. The scenario is this…let’s say you have a JavaScript method containing an Ext.Ajax.Request with a callback function. Furthermore, you need to pass a couple of variables to this method and have them processed in the callback function. The scenario in code looks like…

var someClass = {
     someMethod: function(var1,var2) {
            Ext.Ajax.request({
                 url: 'someURL.php',
                 method: 'POST',
                 params: {param1:'param1',param2:'param2'},
                 success: function(response) {
                 // Do something with response.responseText AND var1, var2 here.
           }
        });
     }
}

At first glance this presents a big scoping problem since var1 and var2 are local and available only to someMethod. The answer is the ’scope’ parameter of the Ajax.request object. If we set the scope parameter to someClass.someMethod we now have access to var1 and var2 inside the success callback function.

var someClass = {
     someMethod: function(var1,var2) {
          Ext.Ajax.request({
               url: 'someURL.php',
               method: 'POST',
               scope: someClass.someMethod,
               params: {param1:'param1',param2:'param2'},
               success: function(response) {
                    // We now have access to var1 and var2.
                    alert('Response = '+response.responseText+' var1 = '+var1+' and var2 = +var2);
               }     
          });
     }
} 

Add Your Comments