2

I am trying to call a second function after a first function is complete with an ajax call. I was doing this previously by calling the second function in the success portion of the first function like so

function1(){
    $.ajax({
       success: function(results)
            function2(results);
    })
}

I am trying to make this more elegant and not tie these functions together. I just started experimenting with $.promise()

I am trying to write code that would look something like this

function1().promise().done(function(results){
    function2(results);
});

function1({
   $.ajax({
       success: function(results){
            return results;
       }
   })
})

I could be going about this the completely wrong way. Any advice would be helpful

dan_vitch
  • 4,477
  • 12
  • 46
  • 69

1 Answers1

2

You have to return the promise that is returned by $.ajax:

function1() {
   return $.ajax({...});
}

function1().done(function2);

.promise, the function you are referring to, is a method of a jQuery object. But $.ajax doesn't return a jQuery object, it returns a jqXHR object, which directly implements the promise interface.

See also: How do I return the response from an asynchronous call? and the jQuery documentation: http://learn.jquery.com/code-organization/deferreds/.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    Pretty sure you can do `$.ajax().promise()`, but that doesn't do anything, as `$.ajax()` is already a promise. You only need `promise()` when doing something like `var d = new $.Deferred;`. – gen_Eric Aug 26 '13 at 19:20