Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to $.then function

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.

like image 416
Gregg Avatar asked Jul 23 '13 14:07

Gregg


2 Answers

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 */ });
like image 67
Jason P Avatar answered Sep 28 '22 18:09

Jason P


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);
});
like image 34
meagar Avatar answered Sep 28 '22 18:09

meagar