Antonio Laguna
Antonio Laguna

Reputation: 9292

Executing function after async operation has been performed

I'm having some issues because I'm trying to re-use code (which can be used) in other parts of my application.

Now, I'm having the common:

$.ajax({
   url: JSONurl,
   dataType: "json",
   cache: false,
   data: params,
   success: function(data){
      // do stuff after the result is retrieved
   }
});

The stuff is going fine but I would want to do something like that:

function ultramegafunction (){
    var ajax_data = asyncAjaxFunction();
    // When ajax_data is filled do other stuff
}

In that way, I could use the asyncAjaxFunction() in other functions where it's needed without having to rewrite all the code and putting specific things in the success part.

Do someone knows how could I do that?

Upvotes: 1

Views: 160

Answers (2)

Ankur
Ankur

Reputation: 791

Try this...

"asyncAjaxFunction" = function(options){
    var xhr = $.ajax( {
        'url' : options.url,
        'dataType' : (options.dataType) ? options.dataType : 'JSON',
        'type' : (options.type) ? options.type : 'GET',
        'async' : (options.async) ? options.async : false,
        'data' : (options.data) ? options.data : '',
        'cache' : (options.cache) ? options.cache : false,
        'success' : (options.success)? (options.success) :function(data) {
        },
        'error' : (options.error)? (options.error) :function() {
        }
    });
    return (xhr.status === 200) ? xhr.responseText : '';

}

Now you can call asyncAjaxFunction() from any where with appropriate parameters.

Upvotes: -1

jAndy
jAndy

Reputation: 236022

Use jQuerys Deferred objects which implicitly are mixed into the jXHR object. Therfore you need to return the jXHR object and then also bound handlers at some other place.

function asyncAjaxFunction() {
    return $.ajax({
        url: JSONurl,
        dataType: "json",
        cache: false,
        data: params,
        success: function(data){
           // do stuff after the result is retrieved
        }
    });
}

and somewhere else

function ultramegafunction (){
    asyncAjaxFunction().done(function( ajaxData ) {
        // When ajax_data is filled do other stuff
    });
}

Ref.: http://api.jquery.com/category/deferred-object/

Upvotes: 2

Related Questions