'Jquery Triggers Not Working After Ajax Calling

I have 2 pages of PHP, "booking.php" and "fetch_book_time.php".

Inside my booking.php (where the jquery trigger is)

<?php
    include ("conn.php");
    include ("functions.php");
?>
$(document).ready(function(){
    $(".form-group").on("change", ".ajax-venue", function(){
        $(".ajax-date").trigger("change"); // if .ajax-venue is changed,
    });                                    // then trigger change on .ajax-date

    $(".form-group").on("change", ".ajax-date", function(){
        // var getData = all my data here

        $.ajax({
            type: "POST",
            url: "fetch_book_time.php",
            data: getData,
            cache: false,
            success: function(getTime){
                $("#ajax-time").html(getTime);
            }
        });
    });
});

The HTML

<div class="form-group">
    Venue: <br>
    <select id='ajax-venue' class="ajax-venue">
        <?php
        $sql = mysqli_query($conn, "SELECT * FROM slot");
        while($row=mysqli_fetch_array($sql)){
            echo "<option value='".$row['slot_venue']."'>".$row['slot_venue']."</option>";
        }
        ?>
    </select>
</div>
<div class="form-group">
    Date: <br>
    <input id="ajax-date" type="date" class="ajax-date"></input>
</div>
<div id="ajax-time" class="form-group">
    Start Time:<br>
    <input id="ajax-sTime" class="ajax-sTime" type="time"></input><br>
    End Time:<br>
    <input id="ajax-eTime" class="ajax-eTime" type="time"></input>
</div>

inside my fetch_book_time.php (ajax page)

<?php
    include ("conn.php");
    include ("functions.php");

    // code and logic here then echo back the codes below

    // input sent back to booking.php into #ajax-time
?>

After cranking up my head for hours, I finally found out that the problem lies in my include files in fetch_book_time.php.

If I removed the include files from fetch_book_time.php the Jquery triggers can work as what I wanted, which is to trigger a change on the date input every time the venue has been changed.

Any solution or help would be much appreciated as I am still very new to Jquery and hope to have a progress in this project. Thank you.



Solution 1:[1]

because you are adding new htmls to page, so you have to bind your events after each

success: function(getTime){
                $("#ajax-time").html(getTime);
            }

or simply define your events globally on document:

so change

 $(".form-group").on("change", ".ajax-venue", function(){

to :

$(document).on("change", ".form-group.ajax-venue", function(){

and

$(".form-group").on("change", ".ajax-date", function(){

to :

$(document).on("change", ".form-group.ajax-date", function(){

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mostafa khoramnia