[英]HTML form data not being posted to use in SQL query
this should be simple but I have lost my way simple form on HTML page - select Men, Women or Junior then send that that value to a php page to perform SQL query and find all the Men, Women or Juniors using the variable "$trigen " 使用 AJAX 在 HTML 頁面上顯示結果
如果我手動設置 $trigen 它可以工作,但當我選擇此代碼中列出的表單中的選項時則不行:-
我的 HTML:-
<!DOCTYPE html>
<html>
<div class="entry-content">
<form action="/getcustomer.php" method="POST">
<label for="trigen">Choose a gender:</label>
<select id="trigen" name="trigen">
<option value="Men">Men</option>
<option value="Women">Women</option>
<option value="Junior">Junior</option>
</select>
<button class="btn btn-primary text-center btn-block btn-flat" style="h2; margin: 20px; color:black; " name="trilookup" type="submit" onclick="showResults()"> Search</button>
</form>
</div>
<div id="results">Results go here if it works....</div>
<script>
function showResults(str) {
var xhttp;
if (str == "") {
document.getElementById("results").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
xhttp.send();
}
</script>
然后是“getcustomer.php”中的我的 php 代碼
<?php
//connect to the database
$conn=mysqli_connect('localhost','wetsuder_user1','user123','wetsuder_finder');
if($conn){
}
else{
echo "Sorry there is a connection error".mysqli_connect_error();
}
$trigen=$_POST['trigen'];
//this is the search
$sql = "SELECT id, Gender, Wetsuit FROM wp_wetsuitdata WHERE Gender = '$trigen'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["Gender"]." ".$row["Wetsuit"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
您的button
導致表單提交。 只需將preventDefault()
添加為showResults
function 的第一行,它將阻止表單自然提交。 您正在通過 ajax 處理表單提交。 出於同樣的原因,您也不需要在<form
標記上使用操作或方法。 另一種阻止表單提交的方法是這樣的: <form onsubmit="return false"
此外,更改您的 function 以找到您要發送的值,因為您實際上並沒有通過 function 調用str
傳遞該值
function showResults() {
preventDefault(); // prevents form submission
// get the value
let str = document.getElementById('trigen').value;
// check to make sure it's there...
if (!str) return alert("Please select an option...");
var xhttp;
......
您通過 GET 發送數據(當您在 URL 上使用?q=val 時,數據正在通過 GET 發送。因此,您可以在 PHP 中接收它:
$trigen=$_GET['q'];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.