0

I'm currently working on a project using Laravel platform. I'm trying to delete data from a model asynchronously using ajax. And when all is done my data should be removed from the table. My code runs perfectly, data are being removed from my database , yet "tr" elements arent really faded or removed. Here is my code : ajax sucess not really working.

$(document).on('click', '.btn-remove-interview' , function() {

    var id = $(this).attr('data-interview-id');
    $.ajax({
        url: './manage/interviews/destroy/'+id ,
        type: 'post',
        dataType: 'json',
        data: id,
        success: function (data) {
            $(this).parents("tr").remove();
        }
    });

});
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
Mohmd Ali
  • 55
  • 8
  • Please paste your code here. Links die. – Jeremy Harris Jul 28 '16 at 17:06
  • $(document).on('click', '.btn-remove-interview' , function() { var id = $(this).attr('data-interview-id'); $.ajax({ url: './manage/interviews/destroy/'+id , type: 'post', dataType: 'json', data: id, success: function (data){ $(this).parents("tr").remove(); } }); }); – Mohmd Ali Jul 28 '16 at 17:07

3 Answers3

1

Use

$(this).closest('tr').remove();

Instead of

$(this).parents("tr").remove();
jonju
  • 2,711
  • 1
  • 13
  • 19
1

The problem is that the success function callback within your ajax request no long refers to the button when you use this. You need to get an explicit variable to the button if you want to use it.

$(document).on('click', '.btn-remove-interview' , function() {

    // Get this button as a variable so we can use it later
    var el = $(this);

    var id = $(this).attr('data-interview-id');

    $.ajax({
        url: './manage/interviews/destroy/'+id ,
        type: 'post',
        dataType: 'json',
        data: id,
        success: function (data) {
            $(el).parents("tr").remove();
        }
    });

});
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
  • i didn't get it well , so i add a new id or class for my tr ? – Mohmd Ali Jul 28 '16 at 17:14
  • Take a look at this: http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback – Jeremy Harris Jul 28 '16 at 17:15
  • Yes. And then inside the `success` callback you need to use `el` instead of `this` because `this` now refers to the closure it is inside of and not the outer element. – Jeremy Harris Jul 28 '16 at 17:18
  • Without seeing your HTML structure, its hard to tell if the code is correct. Is the element with class `btn-remove-interview` INSIDE of the `tr`? Do like @jonju said and use `closest()` instead. https://www.sitepoint.com/jquerys-closest-parents/ – Jeremy Harris Jul 28 '16 at 17:21
  • it tried @jonju way but it didnt work , you want to check my HTML code ? – Mohmd Ali Jul 28 '16 at 17:44
0

Solution was by removing dataType json . My function doesnt return any data .

Mohmd Ali
  • 55
  • 8