【发布时间】:2018-04-23 21:17:24
【问题描述】:
我目前正在 Wordpress 上创建网站,需要通过 ajax 提交表单,是否可以在不使用 Wordpress 功能的情况下执行此操作?我当前的代码没有错误,并且在不更新数据库的情况下返回成功消息。我不明白为什么它不起作用请看看我的简化版 -
这是 HTML 格式 -
<form action="" method="post" id="formAppointment" name="appointmentform">
<input type="text" name="message_first_name" value="" placeholder="First name" id="appointmentFirstName">
<input type="text" name="message_last_name" value="" placeholder="Last name" id="appointmentLastName">
<input type="tel" name="message_phone" value="" placeholder="Phone" id="appointmentPhone">
<input type="submit" id='appointmentSubmit' class='xAnim' name="submit">
</form>
这是 jquery AJAX -
$("#formAppointment").submit(function(e){
var firstname = $("#appointmentFirstName").val();
var lastname = $('#appointmentLastName').val();
var phone = $('#appointmentPhone').val();
var dataString = 'message_first_name='+ firstname + '&message_last_name=' + lastname + '&message_phone=' + phone;
if(firstname.trim() == "" || lastname.trim() == "" || phone.trim() == ""){
alert('missing information');
e.preventDefault();
} else {
// AJAX Code To submit Form.
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
cache: false,
success: function(result){
console.log(dataString);
alert('success');
}
});
}
return false;
});
这是位于 process.php 中的 php
include "config.php";
$patientfirstname = htmlspecialchars($_POST['message_first_name']);
$patientlastname = htmlspecialchars($_POST['message_last_name']);
$patientcontactnumber = htmlspecialchars($_POST['message_phone']);
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO data_table (firstname, lastname, phonenumber ) VALUES ('$patientfirstname', '$patientlastname', '$patientcontactnumber')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
【问题讨论】:
-
在提交时执行 ajax 请求时必须执行
preventDefault(),以防止表单提交/页面重新加载 -
页面已经没有重新加载,正在显示成功消息但没有提交表单数据
-
您是否检查过您发送的数据是,您收到与否。我的意思是首先返回您在 ajax 请求中发送的数据,以检查您是否在响应中获取数据,然后如果您在响应中获取数据,这意味着 ajax 请求是正确的并且问题出在您的数据库查询不是 ajax 请求。
-
请在帖子 $_POST['message_first_name'] 的地方尝试 $_GET['message_first_name'] 可能会起作用,因为有一次我也遇到了同样的问题。
-
嗯,谢谢,刚刚试过了,没用