hogard hogard - 2 months ago 6
Ajax Question

Passing into ajax success function

I have developed following code, I need to pass exact 'this' value ( because lot of items with this class)in to ajax success function. How to do that.

$(document).on('click', '.address_remove_link', function(e) {
var id = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'inc/controlllers/detele_shipping_addr.php',
data: {
internalId: id
},
success: function(response, this) {
$(this).parent().closest('div').hide(200);
},
error: function(data) {
console.log("error");
}
});
});

Answer

The issue is because the scope of this changes within the success handler function. You can store the outer scope in the click handler function instead. Try this:

$(document).on('click', '.address_remove_link', function(e) {
    var $link = $(this); // store reference here
    var id = $link.attr("data-id");

    $.ajax({
        type: 'POST',
        url: 'inc/controlllers/detele_shipping_addr.php',
        data: {
            internalId: id
        },
        success: function(response) {
            $link.parent().closest('div').hide(200); // to use here
        },
        error: function(data) {
            console.log("error");
        }
    });
});
Comments