坚持使用jQuery动态显示变量

When a user chooses a date from the drop-down list, the number of nights changes according to that new date.

Following this tutorial www.w3schools.com/php/php_ajax_database.asp I wrote the following code, but when I change the date on the list, I just get a message saying undefined in the <div id="stats">

<?php
    $dates = "";
    foreach ($check_ins as $check_in):
        $dates .= '<option value= "' . $check_in['check_in'] . '">' . $check_in['check_in'] . '</option>';
    endforeach;

    $nights = $check_ins[0]['nights'];
    if (!empty($_POST['newDate'])){
        $nights = 0;
        foreach ($check_ins as $check_in):
            if ($check_in['check_in'] === $_POST['newDate']){
                $nights += $check_in['nights'];
            }
        endforeach;
    }

?>

<html>
    <head>
        <title>Bookings stats</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script>
            /*function dynamicDates() {
                var d = $("#dates").val();
                $.post("metrily.php", { newDate: d });
            }*/
            function dynamicDates(newDate){
                if (newDate == ""){
                    document.getElementById("stats").innerHTML = "";
                    return;
                } else {
                    xmlhttp = new XMLHttpRequest();
                    xmlhttp.onreadystatechange = function() {
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                            document.getElementById("stats").innerHTML = xmlhttp.responseTest;
                        }
                    };
                    xmlhttp.open("POST", "hotel.php", true);
                    xmlhttp.send("newDate=" + newDate);
                }
            }
        </script>
    </head>
    <body>
        <b>Check-in: </b>
        <select id="dates" name="check_in" onchange="dynamicDates(this.value)"><?php echo $dates; ?></select>
        <br></br>
        <div id="stats">
            <b>Nights: </b><?php echo $nights; ?>
        </div>

    </body>
</html>

If you have jQuery, use it:

function dynamicDates(newDate){ 
  if (newDate == ""){ 
    $("#stats").empty(); return; 
  } else { 
    $.post("hotel.php",{"newDate":newDate},function(data) { $("#stats").html(data); }); 
  } 
 } 

assuming hotel.php only does some calculation and then

<?php echo $nights; ?>