从下拉列表中获取php变量,无需提交页面



我正试图从下拉菜单中获取一个值,并将其作为php变量传递并回显(在同一页上(。

下拉列表显示用户的名称,但选择他们的用户名,我想回显。如果我能成功地回显它,它的目的是使用变量来执行其他任务。

我使用了jquery和ajax来获取变量,而无需提交页面。但是我无法获取php变量。

我读了几个例子,并使用了它们,但不知何故,我的代码不起作用。谁能告诉我哪里出了错吗?

这是我的代码:

Test2.php

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>
<select name="user" id="user" >
<option disabled selected value> - Select User - </option>
<?php 
$sql_select = mysqli_query($conn,"SELECT username, surname, fname FROM user WHERE v_flag != 0 ORDER BY surname ASC ");
while ($result = mysqli_fetch_assoc($sql_select)){
$name = ($result['surname']. ', '.$result['fname']);
echo '<option value = " '.$result['username']. '">'.$name.'</option>';
}
?>                          
</select>
</td>                   
</tr>
</table>        
<script type="text/javascript">
$(document).ready(function() {
$("#user").change(function() {        
var user = $(this).val();
$.ajax({
url:"test2.php",
data:{username : user},
type:'POST',
success:function(response) {
$("#usermame").html(response);
}
});
});
}); 
</script>
<?php
if (isset($_POST['username'])){
$username = $_POST['username'];     
if (!empty($username)){
echo 'You have selected user: '.$username ;
}
}
?>

<?php
if (isset($_GET['username'])){//only echo user name if requested from js do not include header or footer 
$username = $_GET['username'];     
if (!empty($username)){
echo 'You have selected user: '.$username ;
}
}else{//you can include here your headers
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>
<select name="user" id="user" >
<option disabled selected value> - Select User - </option>
<?php 
$sql_select = mysqli_query($conn,"SELECT username, surname, fname FROM user WHERE v_flag != 0 ORDER BY surname ASC ");
while ($result = mysqli_fetch_assoc($sql_select)){
$name = ($result['surname']. ', '.$result['fname']);
echo '<option value = " '.$result['username']. '">'.$name.'</option>';
}
?>                          
</select>
</td>  </tr> <tr><td> <span id="username">
<?php if (isset($_POST['username'])){//show if submitted from html form
$username = $_POST['username'];     
if (!empty($username)){
echo 'You have selected user: '.$username ;
}
}
?>  </span></td>                   
</tr>
</table>        
<script type="text/javascript">
$(document).ready(function() {
$("#user").change(function() {        
var user = $(this).val();
$.ajax({
url:"test2.php?username="+user,
success:function(response) {
$("#username").html(response);
}
});
});
}); 
</script>
<?php
//you can include here your footers
}
?>

您的成功处理程序正在打印一个html元素中的请求内容,该元素的id username在页面上不存在(至少在这个片段中不存在(

success:function(response) {
$("#usermame").html(response);
}

尝试将POST请求发送到另一个文件,因为在您的情况下,打印的内容将再次包含select(和db请求(。

最新更新