Home > Back-end >  after using jquery datatable searching, ajax button call is not working
after using jquery datatable searching, ajax button call is not working

Time:04-29

I am fetching some data from my database using PHP and MySQL. I am using the jQuery datatables plugin. In the table, there is a column containing an "Add" button. When the button is clicked, the Ajax method runs in the background.

The button call works perfectly until I'm changing table data by table pagination, or getting data from the search option from the table. I can't get the value of the data-row-id upon the click on add button.

Here is my PHP code:

<script src="js/jquery.dataTables.min.js"></script>

<table id="basicTable" >
    <thead >
        <tr>
            <th>Coin No</th>
            <th>Coin ID</th>
            <th>Coin Symbol</th>
            <th>Coin Name</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php
            $result = mysqli_query($conn, " SELECT ccl.* FROM coinmarketcap_coin_list ccl WHERE SYMBOL 
            NOT IN(SELECT COIN_SYMBOL FROM fetch_coinmarketcap_coins) ORDER BY ID ASC ");
            $row = mysqli_fetch_array($result);
            $i = 1;

            do {
        ?> 
                <tr data-row-id="<?php echo $row['SYMBOL']; ?>">
                    <td><?php echo $i; ?></td>
                    <td><?php echo $row["COINMARKETCAP_ID"]; ?></td>
                    <td><?php echo $row["SYMBOL"]; ?></td>
                    <td><?php echo $row["COIN_NAME"]; ?></td>
                    <td >
                        <button type="button"  data-id="<?php echo $row['SYMBOL']; ?>" style="float: none;">Add</button>
                    </td>
                </tr>
        <?php 
                $i  ;
            } while ($row = mysqli_fetch_array($result));
        ?>
    </tbody>
</table>

And my client-side code

$(document).ready(function(){
    $('.add').on('click', function() {
        var trObj = $(this).closest("tr");
        var symbol = $(this).closest("tr").attr('data-row-id');
        // var symbol = $(this).attr('data-id');
        console.log(symbol);
        $.ajax({
            type:'POST',
            url:'addCoins.php',
            // dataType: 'json',
            data:{symbol:symbol,action:"addCoinMarketCapCoin"},
            success:function(data) {
                trObj.remove();
                $("#msg").removeClass('alert-danger');
                $("#msg").addClass('alert-success').html("Coin "  symbol " has been added successfully.");  
            }
        });
    });
});

CodePudding user response:

You're seeing a common behavior - when you add new elements to the DOM, then those elements don't have any event handlers bound until you explicitly bind them, e.g. by calling $(newElement).click(...).

jQuery lets you listen for events on a parent element, for example on the <table>:

$('#basicTable').on('click', '.add', function() {
    var $tr = $(this).closest("tr"),
        symbol = $tr.data('row-id');
    $.post('addCoins.php', {
        symbol: symbol,
        action: "addCoinMarketCapCoin"
    }).done(function (data) {
        $tr.remove();
        $("#msg")
            .removeClass('alert-danger')
            .addClass('alert-success')
            .text("Coin "   symbol   " has been added successfully.");  
    }).fail(function (jqXhr, status, error) {
        $("#msg")
            .removeClass('alert-success')
            .addClass('alert-danger')
            .text("Failed to add coin "   symbol);
        console.log(error);
    });
});

This way the event handler is set up in a fixed place, and no matter how much the table contents change, it will always react to the configured events.

  • Related