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.
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 */ });
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With