oshirowanen
oshirowanen

Reputation: 15925

jquery ajax success problem

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?

Upvotes: 3

Views: 1533

Answers (2)

chedine
chedine

Reputation: 2374

Based on the context, $(this) refers different objects. Check out this link What is this? In the second codesample, this refers to the ajax settings object and not the 'ui-delete' element.

Upvotes: 1

Dave Ward
Dave Ward

Reputation: 60580

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();
    }
  });
};

Upvotes: 7

Related Questions