-1

I have currently have this code

$(document).on("click", ".element", function(e){
    e.preventDefault();
    $.ajax({
        type:'POST',
        url: "ajax/ajax-submit.php",
        success:function(data){
            if(data == "success") {
                console.log("deleted upload");
                $(this).parents(".parent-element").remove();
            }
        },error: function(data){}
    });
});

and this is the HTML

<div class="parent-element">
     <div class="container">
          <button class="element">Remove Parent</button>
     </div>
</div>

that $(this) is not working after success of ajax.

What I want is to remove the parent of this .element that is .parent-element.

Note*: This .element is a appended element inside .parent-element.

Mark Salvania
  • 486
  • 3
  • 17
  • which JQuery library have you imported? Also check for syntax on the API page. – Shreyas Oct 02 '18 at 18:39
  • 2
    You need to either use a helper variable to set `this` to or use the context option on the ajax: https://stackoverflow.com/questions/5097191/ajax-context-option – scrappedcola Oct 02 '18 at 18:41
  • Use $('.element').parents(".parent-element").remove(); instead of $(this).parents(".parent-element").remove(); – Chayan Oct 02 '18 at 18:44
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Heretic Monkey Oct 02 '18 at 19:00

1 Answers1

0

Because this is now belongs to success method, add variable oThis and then use in success method to remove

$(document).on("click", ".element", function(e){
    var oThis = this;
    e.preventDefault();
    $.ajax({
        type:'POST',
        url: "ajax/ajax-submit.php",
        success:function(data){
            if(data == "success") {
                console.log("deleted upload");
                $(oThis).parents(".parent-element").remove();
            }
        },error: function(data){}
    });
});
Ali Shahbaz
  • 825
  • 1
  • 7
  • 19