Home > Mobile >  on click event not working after append tbody in ajax call?
on click event not working after append tbody in ajax call?

Time:11-02

I am using php and mysql with jquery to display my data. The initial time my on click event is working on tbody.

But when I append tbody with ajax call it's not working. I am using event delegation with .on

My html table : I am using simple html table to display my data and onclick of any TD adding ajax to append data.

 <table id="NewsTable" class="display" width="100%" cellspacing="0">
            <thead>
                <tr> 
                    <th class="th-sm">Headline</th>
                    <th class="th-sm">Main Category</th>
                </tr>
            </thead>
            <tbody>
                foreach($data as $val){ // php data foreach loop.(ignore)
                      <tr class='".$x  ."className'> // using dynamic class name and id everywhere.
                  <td  class='".$x  ."className1'><?php echo $val['data1']?></td>
                  <td  class='".$x  ."className2'><?php echo $val['data2']?></td>
                </tr>
                }
            </tbody>
        <table>

my ajax call :

$('#NewsTable').on('click','td', function(e) {
            e.preventDefault();
             $.ajax({
                type: "POST",
                url: 'ajax.php',
                data: 'data',
                beforeSend: function() {
                    $('#loader').show();
                },
                success: function(response) {
                    $('#NewsTable tbody').empty();
                    $('#NewsTable tbody').append(response); // data is coming properly here. but Now on click event not working.
                },
                error: function(xhr, status, error) {
                    console.log(error);
                },
            });
});
   

CodePudding user response:

Try changing the selector to target the document like so:

$(document).on('click','#NewsTable td', function(e) {
            e.preventDefault();
             $.ajax({
                type: "POST",
                url: 'ajax.php',
                data: 'data',
                beforeSend: function() {
                    $('#loader').show();
                },
                success: function(response) {
                    $('#NewsTable tbody').empty();
                    $('#NewsTable tbody').append(response); // data is coming properly here. but Now on click event not working.
                },
                error: function(xhr, status, error) {
                    console.log(error);
                },
            });
});

This code $('#NewsTable tbody').empty(); is removing the elements which have listeners attached, and the new ones therefor do not have the click listeners after being appended.

  • Related