noyruto88 noyruto88 - 1 year ago 111
Ajax Question

Click to html element loaded from PHP through jQuery AJAX won't work

I have a page that when clicking a button, the table with "id" attribute will appear which is loaded using jQuery AJAX with php. And in my JavaScript, putting a click event to table cell will not work.

Here's my full code. Hope you can help me.


<!DOCTYPE html>
table, th, td {
border: 1px solid black;

th, td {
padding: 15px;

td.filled {
background-color: red;

background-color: blue;
cursor: pointer;
<button id="avail_seat_button" type="button">Show Available Seats</button>
<div id="table_avail_seat">
<!-- the table will appear here -->

<br />
<input type="number" id="seat_no">

<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/handy_script.js"></script>
<script src="js/available_seats.js"></script>


$date_departure = "2017-10-22";
$time_departure = "6:30 AM - 10:30 AM";
$route = "Sagay-Cebu Via Tolido";

type: "POST",
url: "available_seats.php",
data: {
date_departure: $date_departure,
time_departure: $time_departure,
route: $route

code snippets form reservation.php class

$cell = 0;
for ($row = 1; $row <= 9; $row++) {
echo "<tr>";
for ($col = 1; $col <= 5; $col++) {
if (in_array($cell, $array_seats)) {
//mark as not available
echo "<td class='filled'>";
echo $cell;
echo "</td>";
} else {
//mark as available
echo "<td class='unfilled'>";
echo $cell;
echo "</td>";
echo "</tr>";


$("td.unfilled").on("click", function() {
alert("hello world");


include "php_library/SiteBasics.php";
include "php_library/Reservation.php";

$reservation = new Reservation;

Answer Source

Have you tried to put this function

$("td.unfilled").on("click", function() {
    alert("hello world");

inside the success of your ajax which replaces the html or you can simply replace this

$("td.unfilled").on("click", function() {
        alert("hello world");

with this

 $(document).on('click', 'td.unfilled', function(){
  alert("hello world");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download