JQuery - making custom function calls ok

I am using jQuery 1.9.1. I have a custom function that does some operations and then makes a $ .ajax call. I would like to call this function in sequence. I tried $ .when but it doesn't solve my problem.

function func(param) {
    //some operations
    $.ajax()
}

main() {
    //first call
    func(param1);
    //wait for done and the run the second
    func(param2);
}

      

+3


source to share


2 answers


You can return the ajax call to you as a deferred one that gives you access to the function done

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

Check out Shauna's answer for a deeper explanation of ajax.



function func(param) {
    //some operations
    return $.ajax()
}

main() {
    //first call
    func(param1).done(function(){
       //wait for done and the run the second
       func(param2);
    });

}

      

+4


source


AJAX calls are asynchronous, which means you can never call them for you to.

Instead, you want to use callback functions in the call $.ajax()

. You would get something like this:

function func(param) {
   // Other stuff
   $.ajax({
      success: func(param2)
   })
}

      



Be careful with infinite loops though, since you are calling the same function. It might be worth looking at the jQuery source for the method ajax()

and seeing how they handle callbacks and writing your methods in a similar way so you can end up with something like:

main() {
   func(param1, {success: func(param2)});
}

      

(Note: $.ajax()

has a parameter async

that you can set to false, but IMO it's a good idea to get a good idea of ​​how AJAX and callbacks work because you will be working with the intended behavior, not against it, which is will eventually save you some headaches.Also, large synchronous AJAX calls can make your site unresponsive, which is bad for your user.)

+6


source







All Articles