如果数据库连接失败,Ajax post响应将返回空白。

huangapple go评论56阅读模式
英文:

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:

&lt;?php
require __DIR__ . &#39;/../config_db.php&#39;;
if ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;) {
// Retrieve the submitted values
$article = $_POST[&quot;article&quot;];
$author = $_POST[&quot;author&quot;];
$tags = $_POST[&quot;tags&quot;];
// Create a new database connection
$connection = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($connection-&gt;connect_error) {
$response = array(
&quot;status&quot; =&gt; &quot;error&quot;,
&quot;message&quot; =&gt; &quot;Error: Failed to connect to the database.&quot;
);
} else {
// Prepare the statement
$stmt = $connection-&gt;prepare(&quot;INSERT INTO article (article, author, tags) VALUES (?, ?, ?)&quot;);
// Bind parameters to the statement
$stmt-&gt;bind_param(&quot;sss&quot;, $article, $author, $tags);
if ($stmt-&gt;execute()) {
$response = array(
&quot;status&quot; =&gt; &quot;success&quot;,
&quot;message&quot; =&gt; &quot;Article submitted successfully!&quot;
);
} else {
$response = array(
&quot;status&quot; =&gt; &quot;error&quot;,
&quot;message&quot; =&gt; &quot;Error: &quot; . $stmt-&gt;error
);
}
// Close the statement
$stmt-&gt;close();
// Close the database connection
$connection-&gt;close();
}
// Send the JSON response
header(&#39;Content-Type: application/json&#39;);
echo json_encode($response);
}
?&gt;

And here's the html form with ajax:

 &lt;form method=&quot;post&quot; action=&quot;submit_article.php&quot; id=&quot;articleForm&quot;&gt;
&lt;div class=&quot;field&quot;&gt;
&lt;div class=&quot;control&quot;&gt;
&lt;textarea class=&quot;textarea&quot; id=&quot;article&quot; name=&quot;article&quot; placeholder=&quot;Enter the article...&quot; required&gt;&lt;/textarea&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;field&quot;&gt;
&lt;div class=&quot;control&quot;&gt;
&lt;input class=&quot;input&quot; type=&quot;text&quot; id=&quot;author&quot; name=&quot;author&quot; placeholder=&quot;Author name...&quot; required&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;field&quot;&gt;
&lt;div class=&quot;control&quot;&gt;
&lt;input class=&quot;input&quot; type=&quot;text&quot; id=&quot;tags&quot; name=&quot;tags&quot; placeholder=&quot;Add some tags...&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;field is-grouped&quot;&gt;
&lt;div class=&quot;control&quot;&gt;
&lt;input class=&quot;button is-link&quot; type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;control&quot;&gt;
&lt;input class=&quot;button is-link is-light&quot; type=&quot;button&quot; value=&quot;Cancel&quot; onclick=&quot;window.location.href=&#39;index.php&#39;&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;div id=&quot;notification&quot; class=&quot;notification is-primary&quot;&gt;&lt;/div&gt;
&lt;script&gt;
$(document).ready(function() {
$(&quot;#articleForm&quot;).submit(function(e) {
e.preventDefault(); // Prevent form submission
// Send the form data via AJAX
$.ajax({
url: &quot;submit_article.php&quot;,
type: &quot;POST&quot;,
data: $(this).serialize(),
success: function(response) {
// Display the notification message
var notification = $(&quot;#notification&quot;);
notification.text(response[&#39;message&#39;]);
notification.fadeIn().delay(3000).fadeOut();
// Clear the form
$(&quot;#article&quot;).val(&quot;&quot;);
$(&quot;#author&quot;).val(&quot;&quot;);
$(&quot;#tags&quot;).val(&quot;&quot;);
},
error: function(xhr, status, error) {
// Display the error message
var notification = $(&quot;#notification&quot;);
notification.text(response[&#39;message&#39;]);
notification.fadeIn().delay(3000).fadeOut();
console.log(error); // Log any errors to the console
}
});
return false; // Prevent default form submission
});
});
&lt;/script&gt;

答案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-&gt;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-&gt;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.

huangapple
  • 本文由 发表于 2023年6月22日 01:18:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525719.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定