Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ajax success problem

Tags:

jquery

Why is it that the following script works clientside by removing the relievant html entity:

$(".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 proper", does not work by removing the html entity?

$(".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 does both clientside and serverside correctly, the second script does serverside correctly, but on clientside, it just displays an alert "success", but does not remove the html entity "widget"

Any ideas?

like image 515
oshirowanen Avatar asked Jun 03 '26 10:06

oshirowanen


1 Answers

Within the success handler, this isn't what it was in your click handler (it's the XMLHttpRequest object that $.ajax used).

Capture a reference to the this you're interested in before the $.ajax call:

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

  $.ajax({
    // etc.
    success: function() {
      $(that).parents('.widget:first').remove();
    }
  });
};
like image 101
Dave Ward Avatar answered Jun 06 '26 01:06

Dave Ward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!