英文:
Ajax post response returns empy if database connection fails
问题
我正在构建一个PHP项目,其中包含一个具有3个字段的简单表单。该表单与名为“article”的MySQL表相连接。当我提交表单时,借助jQuery和Ajax,我会显示一个通知消息,例如“成功提交”(成功提交)或“出了些问题”(提交失败)。我的问题是,这个通知消息在成功提交时工作正常,但是如果出现错误 - 例如如果数据库连接失败 - 那么通知消息就是空的,不会显示错误消息!我在我的代码中添加了 console.log(error);
,以便我可以在控制台中检查错误,但那里没有显示任何错误。我做错了什么?
以下是我为在数据库中提交表单而编写的PHP代码:
<?php
require __DIR__ . '/../config_db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// 检索提交的值
$article = $_POST["article"];
$author = $_POST["author"];
$tags = $_POST["tags"];
// 创建一个新的数据库连接
$connection = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($connection->connect_error) {
$response = array(
"status" => "error",
"message" => "错误:无法连接到数据库。"
);
} else {
// 准备语句
$stmt = $connection->prepare("INSERT INTO article (article, author, tags) VALUES (?, ?, ?)");
// 将参数绑定到语句
$stmt->bind_param("sss", $article, $author, $tags);
if ($stmt->execute()) {
$response = array(
"status" => "success",
"message" => "文章提交成功!"
);
} else {
$response = array(
"status" => "error",
"message" => "错误:" . $stmt->error
);
}
// 关闭语句
$stmt->close();
// 关闭数据库连接
$connection->close();
}
// 发送JSON响应
header('Content-Type: application/json');
echo json_encode($response);
}
?>
以下是带有Ajax的HTML表单:
<form method="post" action="submit_article.php" id="articleForm">
<div class="field">
<div class="control">
<textarea class="textarea" id="article" name="article" placeholder="输入文章..." required></textarea>
</div>
</div>
<div class="field">
<div class="control">
<input class="input" type="text" id="author" name="author" placeholder="作者名..." required>
</div>
</div>
<div class="field">
<div class="control">
<input class="input" type="text" id="tags" name="tags" placeholder="添加一些标签...">
</div>
</div>
<div class="field is-grouped">
<div class="control">
<input class="button is-link" type="submit" value="提交">
</div>
<div class="control">
<input class="button is-link is-light" type="button" value="取消" onclick="window.location.href='index.php'">
</div>
</div>
</form>
<div id="notification" class="notification is-primary"></div>
<script>
$(document).ready(function() {
$("#articleForm").submit(function(e) {
e.preventDefault(); // 阻止表单提交
// 通过AJAX发送表单数据
$.ajax({
url: "submit_article.php",
type: "POST",
data: $(this).serialize(),
success: function(response) {
// 显示通知消息
var notification = $("#notification");
notification.text(response['message']);
notification.fadeIn().delay(3000).fadeOut();
// 清除表单
$("#article").val("");
$("#author").val("");
$("#tags").val("");
},
error: function(xhr, status, error) {
// 显示错误消息
var notification = $("#notification");
notification.text(response['message']);
notification.fadeIn().delay(3000).fadeOut();
console.log(error); // 将任何错误记录到控制台
}
});
return false; // 阻止默认表单提交
});
});
</script>
英文:
I am building a PHP project that has a simple form with 3 fields. This form is connected with a MySQL table named "article". When I submit the form, with the help of jQuery and Ajax I display a notification message: eg "Submitted successfully" on success submission or "Something went wrong" on fail submission. My problem is that this notification message works fine on successful submission but if there is an error - For example if database connection fails - then the notification message is empty and it doesn't display the error message! I added the console.log(error);
in my code so I can check the console for errors but there are no errors displayed there. What I 'm doing wrong?
Here is the PHP code I wrote for submit the form in the DB:
<?php
require __DIR__ . '/../config_db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve the submitted values
$article = $_POST["article"];
$author = $_POST["author"];
$tags = $_POST["tags"];
// Create a new database connection
$connection = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($connection->connect_error) {
$response = array(
"status" => "error",
"message" => "Error: Failed to connect to the database."
);
} else {
// Prepare the statement
$stmt = $connection->prepare("INSERT INTO article (article, author, tags) VALUES (?, ?, ?)");
// Bind parameters to the statement
$stmt->bind_param("sss", $article, $author, $tags);
if ($stmt->execute()) {
$response = array(
"status" => "success",
"message" => "Article submitted successfully!"
);
} else {
$response = array(
"status" => "error",
"message" => "Error: " . $stmt->error
);
}
// Close the statement
$stmt->close();
// Close the database connection
$connection->close();
}
// Send the JSON response
header('Content-Type: application/json');
echo json_encode($response);
}
?>
And here's the html form with ajax:
<form method="post" action="submit_article.php" id="articleForm">
<div class="field">
<div class="control">
<textarea class="textarea" id="article" name="article" placeholder="Enter the article..." required></textarea>
</div>
</div>
<div class="field">
<div class="control">
<input class="input" type="text" id="author" name="author" placeholder="Author name..." required>
</div>
</div>
<div class="field">
<div class="control">
<input class="input" type="text" id="tags" name="tags" placeholder="Add some tags...">
</div>
</div>
<div class="field is-grouped">
<div class="control">
<input class="button is-link" type="submit" value="Submit">
</div>
<div class="control">
<input class="button is-link is-light" type="button" value="Cancel" onclick="window.location.href='index.php'">
</div>
</div>
</form>
<div id="notification" class="notification is-primary"></div>
<script>
$(document).ready(function() {
$("#articleForm").submit(function(e) {
e.preventDefault(); // Prevent form submission
// Send the form data via AJAX
$.ajax({
url: "submit_article.php",
type: "POST",
data: $(this).serialize(),
success: function(response) {
// Display the notification message
var notification = $("#notification");
notification.text(response['message']);
notification.fadeIn().delay(3000).fadeOut();
// Clear the form
$("#article").val("");
$("#author").val("");
$("#tags").val("");
},
error: function(xhr, status, error) {
// Display the error message
var notification = $("#notification");
notification.text(response['message']);
notification.fadeIn().delay(3000).fadeOut();
console.log(error); // Log any errors to the console
}
});
return false; // Prevent default form submission
});
});
</script>
答案1
得分: 1
使用$connection->connect_error
将为您提供关于已知错误的错误,例如错误的用户名/密码/权限等。
真正的连接问题将导致new mysqli($servername, $username, $password, $dbname);
抛出异常。因此,您的脚本将被通用异常处理程序简单地中断,由于$connection->connect_error
引发的错误响应将永远不会生成。
为了解决这个问题,您需要使用try/catch块并在其中生成适当的响应。
更新:
使用mysqli_report(MYSQLI_REPORT_STRICT);
,您可以强制mysqli对已知错误抛出异常 - 然后您可以省略额外的If
检查并在catch块中处理所有内容。
英文:
using $connection->connect_error
will give you an error for well known errors, such as wrong user / password / permission, etc.
Having a real connection issue will cause new mysqli($servername, $username, $password, $dbname);
to throw an exception. Hence your script is simply interrupted by the generic exception handler and the error-response you are generating due to $connection->connect_error
will never be generated.
To cover that, you need to use a try/catch-block and generate a proper response there.
Update:
With mysqli_report(MYSQLI_REPORT_STRICT);
you can force mysqli to throw exceptions for well known errors as well - then you can ommit the additional If
check and handle everything from within the catch-block.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论