GauteR
GauteR

Reputation: 360

Ext JS 4.1.3: Returning values with Ext.Ajax.request

This might be a silly question, but I have been struggling with the following piece of code in my Ext JS 4.1.3 application:

getInvestmentFee_Percentage : function() {
    var rVal = 0;

    Ext.Ajax.request({ 
        url : 'index.php/ajax/getcountryinvestmentfeepercentage/', 
        success : function(transport, json) {
             try {
                  var JSONResponse = Ext.JSON.decode(transport.responseText);
             } catch (e) {
                  return false;
             }

             if(JSONResponse.success == true || JSONResponse.success == "true") {
                  var investTax = 1+parseFloat(JSONResponse.results[0].constantValue);
                  console.log(investTax);
                  // TODO Return investTax
                  return investTax;
             } else {
                  return false;
             }
        },
        failure : function(transport, json) {
            return false;
        }
   });

    return rVal;
}

I'm trying to write to the rVal variable, but since the Ext.Ajax.request is a different object, it will not do so. How do I return the value for use outside the AJAX request? I could of course write to global variables, but I doubt it's the right way to do this.

Any suggestions appreciated.

Upvotes: 1

Views: 2492

Answers (1)

sra
sra

Reputation: 23973

You simply cannot do it this way cause the getInvestmentFee_Percentage will (may) be exiting before the success or failure callback method gets called but anyway they are in a different scope.

So only the (a) callback method will be able to return a value, but this will be (most commonly) done in the scope of the callbackmethod. For sure you can define the callback methods within your current function but it will be all the same, your method will exit.

I guess you should rethink your implementation here.

  • One approach may to use a custom event that the caller of getInvestmentFee_Percentage subscribe
  • Or the caller of getInvestmentFee_Percentage sends a callback (and if required a scope) as argument which you can then use

Both would work.

Upvotes: 2

Related Questions