I have 2 different set of codes, the only difference is the location of $(this).closest('.organizer_listing').slideUp('fast');. In the first set of code, it works, but I prefer for that line of code to be as in the 2nd set of code inside the callback function, which no longer works – slideUp does not seem to be executed.
Why is this so? How should I fix it?
Variation 1
$("input[type=checkbox]:checked").each(function() {
$(this).closest('.organizer_listing').slideUp('fast'); // Remove listings visually from list
// Send AJAX request to delete from database
var listing_id = $(this).closest('.organizer_listing').data('listing_id');
$.ajaxSetup({ cache: false });
$.getJSON(base_url + 'organizer/delete_favorite',
{listing_id: listing_id},
function(json) {
$.modal.close();
});
});
Variation 2
$("input[type=checkbox]:checked").each(function() {
// Send AJAX request to delete from database
var listing_id = $(this).closest('.organizer_listing').data('listing_id');
$.ajaxSetup({ cache: false });
$.getJSON(base_url + 'organizer/delete_favorite',
{listing_id: listing_id},
function(json) {
$.modal.close();
$(this).closest('.organizer_listing').slideUp('fast'); // Remove listings visually from list
});
});
Variation two doesn’t work because in your
$.getJSONcallback,thisis no longer the current element in youreachloop, but rather thejqXHRobject.You can easily work around this by saving the value of
thisto a new variable, which your callback will “close over” (have access to):