如何使用AJAX更新动态填充的内容

时间:2014-12-04 00:10:47

标签: php jquery html ajax json

我有一些代码填充如下:

<select class="form-control" name="accommodation_ID" id="accommodation_ID">
    <option value="-1">-- Please Select --</option>
    <?php
        $AccomodationID = 13; //For testing purposes
        $accommodation_query = mysqli_query($conn,"SELECT ENTITIES.LastName, 
                               ACCOMMODATION.AccomodationID, ACCOMMODATION.PUPoint 
                               FROM ACCOMMODATION, ENTITIES WHERE ENTITIES.Entity_ID = 
                               ACCOMMODATION.Entity_ID")
                                    or die("Error: ".mysqli_error($conn));  
        while($accommodation_Results = mysqli_fetch_array($accommodation_query)){
            if($accommodation_Results['AccomodationID'] == $AccomodationID){
                echo '<option selected value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
                $PUPoint = $accommodation_Results['PUPoint'];
            }
            else{
                echo '<option value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
            }
        }
   ?>
   </select>
   <label>Pick Up Point</label>
   <input type="text" name="PUPoint" readonly value="<?php echo $PUPoint; ?>">

此代码没有问题,它会检查数据库并查找匹配项,如果是,则将set设置为所选选项,获取PUPoint(拾取点)变量并将其存储在输入字段中。

我现在的问题是,当我从下拉列表中选择不同的选项时,拾取点输入字段不再更新。这就是我在实施上述工作之前所做的工作:

j$('select[name=accommodation_ID]').change(function(event) {
    event.preventDefault();
    var accommodationID = j$(this).val();
    post_data = {'accommodation_ID':accommodationID};
    var data = {
        "action": "Accommodation_Details"
    };
    data = j$(this).serialize() + "&" + j$.param(data);

    j$.ajax({
      type: "POST",
      dataType: "json",
      url: "../include/booking_Modify.php", 
      data: data,
      success: function(data) {
          j$('input[name=PUPoint]').val( data["PUPoint"] );
      },
      error: function (request) {
          console.log(request.responseText);
      }   
    });
});

booking_Modify.php

//checks and switch statement related code

$return = $_POST;
$return["accommodation_ID"] = $_POST["accommodation_ID"];
$return["SQL"] = "SELECT * FROM ACCOMMODATION WHERE AccommodationID = ".$_POST["accommodation_ID"]."";
$query = mysqli_query($conn,"SELECT * FROM ACCOMMODATION WHERE AccomodationID = ".$_POST["accommodation_ID"]."")
    or die("Error: ".mysqli_error($conn));
$row = mysqli_fetch_array($query);
$return["PUPoint"] = $row["PUPoint"];
$return["json"] = json_encode($return);
echo json_encode($return);

我做了一些echoing / console.log并注意到它总是将相同的住宿ID号码(13)传递给booking_Modify.php。现在选择其他选项时,它不会改变。我不知道是不是因为现在应用于选项元素的“已选择”属性。任何想法将不胜感激

1 个答案:

答案 0 :(得分:1)

您已定义了$AccomodationID = 13; //For testing purposes之前在while循环的每次迭代中打印的$accommodation_Results['AccomodationID']而不是当前ID。您可能希望将{{1}}写为选项值。