Home > database >  PHP generated table is not visible to JS script
PHP generated table is not visible to JS script

Time:07-28

Hello I am new to website development (started a couple of days ago).

I have a problem, I am creating a table on the site using PHP. Then I activate the JS script that is supposed to be responsible for selecting the row. However, js does not see the data generated by PHP. If I call the JS code from the browser console the functionality works.

Table:

<div >
    <table id="datatablesSimple">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </tfoot>
        <tbody>
<?php
require 'File.php';
$conn = new \mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM person";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
    while ($row = $result->fetch_assoc())
    {
        echo '<tr>';
        echo '<td>' . $row['name'] . '</td>';
        echo '<td>' . $row['email'] . '</td>';
        if ($row['email'] == 0 or $row['email'] == null)
        {
            echo '<td>NO</td>';
        }
        elseif ($row['statusemail'] == 1)
        {
            echo '<td>YES</td>';
        }
        else
        {
            echo '<td>ERROR</td>';
        }
        echo '</tr>';
    }
}

?>
                                                
        </tbody>
    </table>
</div>

JS file

$("#datatablesSimple tr").click(function(){
   $(this).toggleClass('selected');    
   var value=$(this).find('td:first').html();
   alert(value);    
});

$('.ok').on('click', function(e){
    var selected = [];
    $("#datatablesSimple tr.selected").each(function(){
        selected.push($('td:first', this).html());
    });
    alert(selected);
});

CodePudding user response:

Since you say that from console it's working, then most likely you bind events before actual elements are rendered into DOM. Wrap your code into $(document).ready:

$(document).ready(function () {
    $("#datatablesSimple tr").click(...);
    $('.ok').on('click', ...);
});
  • Related