I've been trying to get this to work for ages, and have read a lot of other answers to similar questions ( How to add AJAX Submit to PHP validation and return message?,ajax submit form why it cannot echo $_POST),但我似乎无法将其付诸实践。
基本上,我尝试制作的是一种注册表单,只需在桌面的新行中插入某人的电子邮件地址,即可衡量访问者的数量。兑换率!不用多说,这是我的剧本,我真诚地希望你能帮助我:)
HTML表单:
0005
send_post php:
instance
Javascript + AJAX:
eureka:
instance:
prefer-ip-address: false
hostname: fqdn.api.stuff.com
nonSecurePort: 65230
为了便于阅读,我只包含了一小部分带有ajax位的JS代码。 PS。当我直接导航到send_post.php时,它会在数据库中创建一个空行。
答案 0 :(得分:1)
这里有很多错误,仅举几例:
e
未定义。答案 1 :(得分:0)
您的数据应该是关键:值格式要正确发布
print [()] == list(tuple()) # prints False
答案 2 :(得分:0)
我认为将请求数据设置为表单对象是不够的:
data: $("#signup-form"),
您需要显式设置表单值或序列化表单对象。 参见例如Pass entire form as data in jQuery Ajax function供参考。
答案 3 :(得分:0)
尝试更新您的Form-Javascript:
$('#signup-form').on('submit', function () {
...
data: { email: $('#email').val() }
...
所以$ _POST ['电子邮件']会以$ _POST ['电子邮件]的形式到达您的PHP后端。
答案 4 :(得分:0)
删除表单以确保在发送正常的POST操作时按钮不刷新站点:
<input type="email" name="email" id="email" placeholder="Email Address" />
<button id="signUpBtn">Sign up</button>
<script src="assets/js/main.js"></script>
send_post.php:
$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "email";
$email = $_POST['email'];
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Insert the data
mysqli_query($conn,"INSERT INTO email (email)
VALUES ('$email')");
$conn->close();
?>
提交表格:
$('#signUpBtn').on("click",function (e) {
$.ajax({
type: "POST",
url: "send_post.php",
data: { email: $("#email").val() },
success: function () {
alert("success");
}
});
e.preventDefault();
return false;
});
这应该可以解决问题。请务必注意我在jQuery部分中所做的更改。
答案 5 :(得分:0)
有一个类似于我的答案,但我的php
部分非常安全,所以这里是代码。
<强> HTML 强>
<form id="signup-form" name="emailform" >
<input type="email" name="email" id="email" placeholder="Email Address" />
<input type="button" id="signup" value="Sign Up" />
</form>
<强> Jquery的强>
$(document).ready(function (){
$(document).on('click', '#signup', function (){
$.ajax({
url: "send_post.php",
type: "POST",
data: {
"emali": $("#email").val()
}
success: function (response) {
alert("response");
}
});
})
})
<强> PHP 强>
<?php
// Fetching Values From URL
$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "email";
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Insert the data
$stmt = $conn -> prepare("INSERT INTO email (email) VALUES (?)");
$stmt -> bind_param('s', $email);
if($stmt -> execute()){
echo "Done";
}else{
echo "Not added";
}
$conn->close();
?>