2

i m trying to remove tr from table using closest function. this function is working properly out of the $.post request but when same script is used in post request its not working. My Code is

$(".delete_cat").click(function() {
        var idd = $(this).val();

        $.post("<?php echo base_url() ?>category/delete",
            {id:idd},
            function(data) {

                if (data === 1) {
                    var tr = $(this).closest('tr').remove();
                    tr.css("background-color","#FF3700");
                    tr.fadeOut(400, function(){
                        tr.remove();
                    });

                }
            }
            )

    })
Hamaad Hussain
  • 111
  • 4
  • 16

3 Answers3

0

That is because context of element is lost in ajax call. you can use context option of ajax to set context of clicked .delete-cart element:

   $.post("<?php echo base_url() ?>category/delete",
   {id:idd},
   context:this,
   function(data) {
     if (data === 1) {
         var tr = $(this).closest('tr').remove();
         tr.css("background-color","#FF3700");
         tr.fadeOut(400, function(){
         tr.remove();
     }
   });

Context option in ajax

Community
  • 1
  • 1
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

this is having different instance inside post success function

$(".delete_cat").click(function() {
  var that = this
  var idd = $(that).val();

  $.post("<?php echo base_url() ?>category/delete", {
      id: idd
    },
    function(data) {

      if (data === 1) {
        var tr = $(that).closest('tr').remove();
        tr.css("background-color", "#FF3700");
        tr.fadeOut(400, function() {
          tr.remove();
        });

      }
    }
  )

})
Tushar
  • 85,780
  • 21
  • 159
  • 179
Kishore Sahasranaman
  • 4,013
  • 3
  • 24
  • 50
0

$(this) inside function is not refer to .delete_cat, but window instead, cache those :

$(".delete_cat").click(function() {
   var $this = $(this);  // <----here
   var idd = $this.val();

    $.post("<?php echo base_url() ?>category/delete",
        {id:idd},
        function(data) {
            if (data === 1) {
                var tr = $this.closest('tr').remove();
                tr.css("background-color","#FF3700");
                tr.fadeOut(400, function(){
                    tr.remove();
                });
            }
   });
});
Norlihazmey Ghazali
  • 9,000
  • 1
  • 23
  • 40