我有这个下拉列表,显示了不同会议的名称。我可以选择某个会议,但是在选择会议时,我想添加一个提交按钮,以便获取所选会议的变量。
我是数据库的新手,但是我尝试添加一个表单,但是我似乎无法使其在php代码中正常工作。数据库连接并显示所有会议都很好,我只是想不出如何获取等于所选选项的变量。
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
//Declare variables
$db_host = "";
$db_username = "";
$db_pass = "";
$db_name = "";
$db_table = "";
//Connect to phpMyAdmin
$con=mysqli_connect("$db_host","$db_username","$db_pass","$db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"$db_name") or die ("No database");
$result=mysqli_query($con,"select * From conferenceList");
echo "<select id='searchddl'>";
echo "<option> -- Search Conference Name -- </option>";
while($row=mysqli_fetch_array($result))
{
echo "<option>$row[name]</option>";
}
echo "</select>";
//Close phpMyAdmin
mysqli_close($con);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css" />
<script>
$("#searchddl").chosen();
</script>
</body>
</html>
我希望变量等于选择的相同对象。所以我希望我的变量等于echo "<option>$row[name]</option>";
enter image description here
答案 0 :(得分:0)
<script>
$( "#searchddl" ).chosen().change(function() { // execute query every time select option changes
var val = $( "#searchddl" ).chosen().val(); // get value from selected option
$.ajax({
url: "myphpfile.php", // call external PHP file for query execution
type: "get",
data: {
myselectvalue: val // passes value as GET parameter (?=myselectvalue=val)
},
success: function(response) {
tmp = response // store variable from PHP output
// do Something
},
error: function(xhr) {
// do Something else
}
});
</script>
在单独的PHP文件中,您可以从get变量中获取值:
if (isset($_GET['myselectvalue']) && strlen($_GET['myselectvalue']) { // make sure it's populated
$valueFromForm = $_GET['myselectvalue'];
// Execute queries, echo results, etc.
}
我在此解决方案中使用GET,但POST也可以正常工作。您只需要在ajax调用中将type: "get"
更改为type: "post"
,在PHP中将$_GET[]
更改为$_POST[]
。