Sandeep Choudhari
Sandeep Choudhari

Reputation: 121

How to return the AJAX value in extJS?

I am calling AJAX request and getting the value as well as a response but I want to return the value and store in a variable. I tried so many ways but its not working. PFB the code snippet.

submitRequest: function(type, url) {
    var maxValue = this.getMaxValue(PORTALURL.EXCEPTION.MAX_VALUE);
    if(grid.getSelectionModel().getSelection().length > maxValue){
        Ext.Msg.alert('Alert!', type + ' count is more than 10');
        return;
    }
}, 
getMaxValue : function(url){
    Ext.Ajax.request({
        url: url,
        success: function(response) {
            var result = Ext.decode(response.responseText);
            //callback(result); Not working
            // return result; Not Working
        }
    });
}

How I can get the value in var maxValue ?

Appreciate all your help.

Upvotes: 0

Views: 2742

Answers (2)

fen1ksss
fen1ksss

Reputation: 1120

Starting from Ext JS 6 you may also use promises with Ext.Ajax.request() out of the box which may help you to organise your code in a more 'straightforward' way and get rid of a so-called 'callback hell'.

submitRequest: function(type, url) {
    this.getMaxValue(PORTALURL.EXCEPTION.MAX_VALUE).then(function(response) {
        var maxValue = Ext.decode(response.responseText);
        if (grid.getSelectionModel().getSelection().length > maxValue){
            Ext.Msg.alert('Alert!', type + ' count is more than 10');
            return;
        }
    }).done();    
}, 

getMaxValue : function(url) {
    return Ext.Ajax.request({
        url: url,
        ...
    })
}

For the further reading I would recommend you the following article https://www.sencha.com/blog/asynchronous-javascript-promises/

Upvotes: 1

Ludovic Feltz
Ludovic Feltz

Reputation: 11916

As an Ajax request is asynchrone you can use a callback:

submitRequest: function(type, url) {
    this.getMaxValue(PORTALURL.EXCEPTION.MAX_VALUE, function(maxValue){ // <<== Your callback
        if(grid.getSelectionModel().getSelection().length > maxValue){
            Ext.Msg.alert('Alert!', type + ' count is more than 10');
            return;
        }
    });
}, 
getMaxValue : function(url, callback){
    Ext.Ajax.request({
        url: url,
        success: function(response) {
            var result = Ext.decode(response.responseText);
            callback(result);
        }
    });
}

Upvotes: 0

Related Questions