在divs中使用ajax php打印值

时间:2018-07-09 10:09:03

标签: php ajax

我有一个表格,用户必须输入他们的预订ID和姓氏。如果数据库中这两个值匹配,那么我需要从数据库中返回相应的值。

到目前为止,一切似乎都正常。正在从数据库中检索正确的值。我想在段落中显示值。我只是不确定如何将其存档。单击该按钮后,将调用ValidateReservation。

这是我的代码:

<p id='guest_full_name'></p>
<p id='unit_number'></p>
<p id='floor'></p>

  <script>
function validateReservation(){
  var reservation_id = document.getElementById("reservation_id").value;
  var guest_last_name = document.getElementById("guest_last_name").value;

$.ajax({
type: 'POST',
url: 'test06.php',
// dataType: 'json',
data: {
    'reservation_id': reservation_id,
    'guest_last_name' : guest_last_name
}, 
success: function(json) {

    console.log(json);
    $('#reservation_id').val(json.reservation_id);
    $('#guest_last_name').val(json.guest_last_name);
    $('#guest_full_name').val(json.guest_full_name);
    $('#unit_number').val(json.unit_number);        
    $('#floor').val(json.floor);
    $('#key_sa').val(json.key_sa);
}, 
error: function(err) {
      console.log(err);
} }); }

test06.php

   <?php

$conn = mysqli_connect("","","","");

$reservation_id=$_POST['reservation_id'];
$guest_last_name=$_POST['guest_last_name'];

$stmt = $conn->prepare("SELECT reservation_id, guest_last_name, guest_full_name, unit_number, floor, key_sa FROM reservations2 INNER JOIN guest ON (reservations2.reservation_id=guest.reservation_idg) INNER JOIN unit USING (unit_id) WHERE reservation_id=? AND guest_last_name=?");
$stmt->bind_param("ss", $reservation_id, $guest_last_name);
$stmt->execute();
$stmt->bind_result($reservation_id, $guest_last_name, $guest_full_name, $unit_number,  $floor, $key_sa);
if ($stmt->errno) {
    die("Query failed to execute: " . $stmt->error);
}
if ($stmt->fetch()) {
    echo json_encode(array("reservation_id" => $reservation_id, 
                           "guest_last_name" => $guest_last_name,  
                           "guest_full_name" => $guest_full_name,  
                           "unit_number" => $unit_number,  
                           "floor" => $floor,  
                           "key_sa" => $key_sa));
} else {
    echo "No matching rows returned.";
}
$stmt->close();

?>

1 个答案:

答案 0 :(得分:1)

请使用.html()而不是.val()

$('#guest_full_name').html(json.guest_full_name);
$('#unit_number').html(json.unit_number);   
$('#floor').html(json.floor);

您也可以在不使用jQuery的情况下使用以下代码

document.getElementById('guest_full_name').innerHTML = json.guest_full_name;
document.getElementById('unit_number').innerHTML = json.unit_number;
document.getElementById('floor').innerHTML = json.floor;

更新: 将您的响应转换为成功函数中的json对象,

var json = JSON.parse(json);