noyruto88 noyruto88 - 1 year ago 134
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.

dynamic_table.html



<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
table, th, td {
border: 1px solid black;
}

th, td {
padding: 15px;
}

td.filled {
background-color: red;
}

td.unfilled:hover{
background-color: blue;
cursor: pointer;
}
</style>
</head>
<body>
<button id="avail_seat_button" type="button">Show Available Seats</button>
<div id="table_avail_seat">
<!-- the table will appear here -->

</div>
<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>
</body>
</html>





available_seats.js



$(document).ready(function(){
$("#avail_seat_button").click(function(){
$date_departure = "2017-10-22";
$time_departure = "6:30 AM - 10:30 AM";
$route = "Sagay-Cebu Via Tolido";

$.ajax({
type: "POST",
url: "available_seats.php",
data: {
date_departure: $date_departure,
time_departure: $time_departure,
route: $route
}
}).done(function(result){
$("#table_avail_seat").html(result);
});
});
});





code snippets form reservation.php class



$cell = 0;
for ($row = 1; $row <= 9; $row++) {
echo "<tr>";
for ($col = 1; $col <= 5; $col++) {
$cell++;
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>";
}





handy_script.js



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





available_seats.php



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

$reservation = new Reservation;
$reservation->available_seats();
?>




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