Yusha Yusha - 27 days ago 6
PHP Question

How to retrieve row from a html table on mouse click in PHP?

I am displaying some records in a HTML table using PHP. I am trying to make it so that when I click on a row, I can store the itemID (that has been clicked on) in a variable on mouse click. For some reason, when I click on the row I want, the alert in javascript just doesn't work nor does it happen. Am I missing something trivial?

<?php
$con=mysqli_connect("localhost","root","mypassword","myDB");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

echo "<font color = 'darkgreen'> Connected to database. </font> <br>";

$result = mysqli_query($con,"SELECT * FROM Inventory");

echo "<table border='1'>
<tr>
<th>Item ID</th>
<th>Item Name</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['itemID'] . "</td>";
echo "<td>" . $row['itemName'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

<script type="text/javascript">
$("tr.table").click(function() {
var tableData = $(this).children("td").map(function() {
return $(this).text();
}).get();

alert("Your data is: " + $.trim(tableData[0]) + " , " + $.trim(tableData[1]));
});
</script>

Answer
<?php
    $con=mysqli_connect("localhost","root","mypassword","myDB");
    // Check connection
    if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    echo "<h3 style='color: darkgreen;'> Connected to database. </h3> <br />";

    $result = mysqli_query($con,"SELECT * FROM Inventory");

    echo "<table border='1'>
    <tr>
    <th>Item ID</th>
    <th>Item Name</th>
    </tr>";

    while($row = mysqli_fetch_array($result))
    {
    echo "<tr>";
    echo "<td class='item-id'>" . $row['itemID'] . "</td>";
    echo "<td class='item-name'>" . $row['itemName'] . "</td>";
    echo "</tr>";
    }
    echo "</table>";

    mysqli_close($con);
    ?>

    <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    <script type="text/javascript">
    $("tr").click(function() {

        var id = $(this).find('.item-id').text();
        var name = $(this).find('.item-name').text();

        alert("Your data is: " + $.trim(id) + " , " + $.trim(name));
    });
    </script>