Problem with jQuery ajax success

Why the following script works on the client side by deleting the relievant html object:

$(".ui-delete").click(function() {

    $.ajax({
        url: 'delete.aspx',
        type: 'POST',
        data: { strWidgetID:$(this).parents(".widget").attr("id") },
        error: function() { alert('Error'); },
        success: function() { alert('Success'); }
    });


    $(this).parents(".widget:first").remove();
});

But the following query, which is โ€œmore correctโ€, does not work when deleting the html object?

$(".ui-delete").click(function() {

    $.ajax({
        url: 'delete.aspx',
        type: 'POST',
        data: { strWidgetID:$(this).parents(".widget").attr("id") },
        error: function() { alert('Error'); },
        success: function() {
            alert('Success');
            $(this).parents(".widget:first").remove();
        }
    });

});

The first script works correctly both on the client side and on the servers, the second script does the servers correctly, but on the client side it simply displays a success warning, but does not delete the html widget object

Any ideas?

+3
source share
2 answers

Inside the success handler, thisthis is not what was in your click handler (this is the XMLHttpRequest object used by $ .ajax).

this, $.ajax:

$(".ui-delete").click(function() {
  var that = this;

  $.ajax({
    // etc.
    success: function() {
      $(that).parents('.widget:first').remove();
    }
  });
};
+7

, $(this) . ? ajax, "ui-delete".

+1

Source: https://habr.com/ru/post/1750446/


All Articles