如果输入更改,则用户填充的框不会更改

时间:2016-09-21 22:58:16

标签: php html mysql ajax

下拉列表是从数据库填充的" meal_planner我试图让下拉列表根据用户选择填充行的其余部分。目前,只有第一个选择工作;如果选择了其他任何内容,它仍然使用第一个选项。我只是把它拼凑在一起。

<?php
$link=mysqli_connect("localhost", "root", "");
mysqli_select_db($link,"meal_planner");
?>
<!DOCTYPE html>
<html>
<head>
<script>
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","getuser.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

<form name="form1" action="" method="post">
<select name="users" onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <?php
  $res=mysqli_query($link,"select name from protein");
  while($row=mysqli_fetch_array($res))
  {
  ?>
  <option><?php echo $row["name"]; ?></option>

  <?php
  }

  ?>

  </select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>

getuser.php

<!DOCTYPE html>
<html>
<head>
<style>
table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','root','','meal_planner');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM protein WHERE protein_id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['name'] . "</td>";
    echo "<td>" . $row['calories'] . "</td>";
    echo "<td>" . $row['protein'] . "</td>";
    echo "<td>" . $row['carbs'] . "</td>";
    echo "<td>" . $row['fats'] . "</td>";
    echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您没有将protein_id放入<option>元素中。

$res=mysqli_query($link,"select name, protein_id from protein");
while($row=mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["protein_id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}

当没有value属性时,它会使用元素的文本,因此您将结束蛋白质名称作为选择值。然后,当您使用intval($q)时,它返回0,因为蛋白质名称不是有效整数,并且AJAX调用中的查询始终使用protein_id = 0获取蛋白质。

相关问题