当我点击“subcribeButton”时,我希望它保存该值并将该值传递给我的PHP文件。我希望该PHP文件然后发布到SQL数据库。
这是我的js:
$(".subscribeButton").on( "click", function() {
var email = $(".subscribeInput").val();
var isValid = isEmailValid(email);
if(isValid){
$(".errorMsg").css( "display", "none" );
modal.style.display = "block";
$.post( "save.php", { email: email });
$(".subscribeInput").val("");
} else {
$(".errorMsg").css( "display", "initial" );
};
});
$(".subscribeInput").on( "click", function() {
$(".subscribeInput").val("");
});
这是我的PHP代码,我希望我的php代码接受来自我的js文件的数据,然后将数据发布到我的sql数据库:
<?php
$servername = "localhost";
$username = "user";
$password = "pw";
$dbname = "db_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = $_POST['email'];
echo $text
$sql = "INSERT INTO MyGuests (email)
VALUES ($text)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
结果是我收到以下错误:
POST http://flockto.it/home/save.php 500 (Internal Server Error)
send @ jquery.js:4
ajax @ jquery.js:4
m.(anonymous function) @ jquery.js:4
(anonymous function) @ email.js:13
dispatch @ jquery.js:3
r.handle @ jquery.js:3
答案 0 :(得分:2)
那么为什么不在你的ajax请求中添加一个回调,这样你就可以在控制台或警报中调试它,看看它可能对你有帮助
$.post( "save.php", { "email" : email } , function(result){
console.log(result);//here the result will display what you will echo after getting the post in your php file
});
所以在你的php文件中你可以添加这个
if (isset($_POST['email'])){
$text = $_POST['email'];
echo $text;
}
//so if you check the console you will get the email
//value from your php file so then you can insert it at the DB as you want
答案 1 :(得分:1)
您遇到语法错误
您的代码缺少此行末尾的;
:
echo $text
应该是:
echo $text;
答案 2 :(得分:0)
解决方案:
在js文件中,网址错误,电子邮件中的引号丢失
$(".subscribeButton").on( "click", function() {
var email = $(".subscribeInput").val();
var isValid = isEmailValid(email);
if(isValid){
$(".errorMsg").css( "display", "none" );
modal.style.display = "block";
$.post( "data/save.php", { "email": email });
$(".subscribeInput").val("");
} else {
$(".errorMsg").css( "display", "initial" );
};
});
$(".subscribeInput").on( "click", function() {
$(".subscribeInput").val("");
});
在php文件中使用了错误的变量
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = $_POST['email'];
if (isset($_POST['email'])){
$text = $_POST['email'];
echo $text;
}
$sql = "INSERT INTO MyGuests (email)
VALUES ('$text')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
百万感谢所有回复此帖子并帮助我解决问题的人。