6

I have something like the following:

$(".remove-item").click(function(e) {
    e.preventDefault();

    var url = $(this).attr('href');
    var id = $(this).data("id");
    $.when(removeItem(url))
      .then(removeItemResponse(id));
});

var removeItemResponse = function(data, id) {
   console.log(data);
   console.log(id);
};

var removeItem = function(url) {
  return $.post(url);
};

The above isn't working in that I get nothing in the logs after the ajax request is processed and I know it has something to do with how I'm addressing the arguments in removeItemResponse. I need to use the returned data from the ajax post but also pass in the id I retrieved in the click function.

4
  • Where is removeItem defined? Commented Jul 23, 2013 at 14:55
  • You've shown us everything but removeItem, could you do that? Commented Jul 23, 2013 at 14:57
  • I don't think removeItem is relevant. Knowing how it is defined won't help with passing id through to the .then callback fn. Commented Jul 23, 2013 at 14:57
  • I added the removeItem function, but I don't believe it really matters. Commented Jul 23, 2013 at 14:59

2 Answers 2

12

removeItemResponse(id) is executing the function immediately, and you aren't passing the result of the first deferred. Try this instead:

.then(function(data) { removeItemResponse(data, id) });

done() also works here:

.done(function(data) { removeItemResponse(data, id) });

You can simplify and handle failures like so:

removeItem(url)
    .done(function(data) { removeItemResponse(data, id) });
    .fail(function(result) { /* do something else */ });
Sign up to request clarification or add additional context in comments.

Comments

2

You're abusing when/then, they don't apply here. Just use .done on the promise returned from removeItem. It will be passed the result of the AJAX request (assuming it's returning the promise returned by a $.ajax invocation or the like), and then you can pass that result and the id on to your handling function:

removeItem(url).done(function (data) {
  removeItemResponse(data, id);
});

2 Comments

I want a separate function to deal with non-200 status response, and it is working in that regard. How am I "abusing" it?
when/then have a specific purpose, and this isn't it. The code you've posted can be accomplished with a single .done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.