所以我的目标是在没有页面重新加载的情况下将一个人添加到我的表单中。 但是当我按提交添加一个人时,信息会通过,但我不会看到它附加到我的下拉列表,我唯一可以看到它的方式是刷新/重新加载页面,我不会# 39;我想做。
的index.php
<form method="post" id="personForm">
First Name: <input type="text" id="firstName" name="firstName"> <br><br>
Last Name: <input type="text" id="lastName" name="lastName"> <br><br>
Favorite Food: <input type="text" id="favoriteFood" name="favoriteFood"> <br><br>
<button type="submit" id="addPersonSubmit" name="addPersonSubmit" class="btn btn-success">Submit</button>
</form>
当用户填写表单并按下提交时,我的javascript将处理它。 &#34; drive.js&#34;
$(document).ready(function(){
$('#personForm').submit(function(e){
e.preventDefault();
addPerson();
});
function addPerson()
{
$.ajax({
type: "POST",
url: "api/people", // api/people
data: $("#personForm").serialize(),
success: function(data,status,xhr)
{
console.log(data);
console.log(status);
console.log(xhr);
console.log($("#personForm").serialize());
console.log("You have added a person");
populatePeople();
displayData();
},
error: function(data,status,xhr)
{
console.log(data);
console.log(status);
console.log(xhr);
console.log($("#personForm").serialize());
console.log("error");
}
});
}
现在,当javascript触发时,它会将该信息发送到我的api.php api.php将检查请求,然后调用insertPerson()函数。
//insert a Person //api/people
function insertPerson()
{
global $connection;
$firstNameEnter = $_POST["firstName"];
$lastNameEnter = $_POST["lastName"];
$foodEnter = $_POST["favoriteFood"];
if(!empty($firstNameEnter) && !empty($lastNameEnter) && !empty($foodEnter))
{
// Insert values into table
$sql = "INSERT INTO People (firstname, lastname, food)
VALUES ('$firstNameEnter', '$lastNameEnter', '$foodEnter')";
// Check if insert is good
if(mysqli_query($connection, $sql))
{
echo "You have added a friend: " . " First Name: ". $firstNameEnter . " Last Name: ". $lastNameEnter . " Food: " . $foodEnter;
}
}
else
{
echo "Error: " . $sql . "<br>" . $connection->error;
}