我在测试 php 网站上的页面上调用一个函数来显示一个 html 表单来记录要通过 ajax 提交到我的 SQL 数据库的数据,但由于某种原因没有插入任何数据。我在包含的 header.php 中有所有必需的引导程序、js、ajax 链接,并且我有其他表单提交到测试站点上同一数据库中的表,这些表单都没有问题,因此数据库连接似乎很好,这是为什么我如此努力地弄清楚为什么没有插入数据。
这是 MAMP 上的本地主机测试服务器,使用 MySQL 5、PHP 5。
我的文件包含在调用时显示 html 条目表单的代码在 functions.php 中:
<?php
session_start();
$link = mysqli_connect("localhost", "user", "pass", "tables");
if (mysqli_connect_errno()) {
print_r(mysqli_connect_error());
exit();
}
// other code ...
function displayTextInput() {
global $link;
echo '
<div class="form">
<div class="form-group">
<textarea class="form-control" id="textDesc" placeholder="Description"></textarea>
<textarea class="form-control" id="textType" placeholder="Type"></textarea>
</div>
<button id="postTextButton" class="btn btn-primary">Post Text</button>
</div>';
}
?>
我的 ajax 调用位于 footer.php 内的脚本中:
<script>
$("#postTextButton").click(function() {
$.ajax({
type: "POST",
url: "actions.php?action=postText",
data: {textDesc: $("#textDesc").val(), textType: $("#textType").val()},
success: function(result) {
if (result == "1") {
alert("ajax successful");
} else if (result != "") {
alert("ajax unsuccessful");
}
}
})
})
</script>
最后我的 SQL 在一个 actions.php 中:
if ($_GET['action'] == 'postText') {
if (!$_POST['TextDesc']) {
echo "Your text description is empty!";
} else {
$textDesc = mysqli_real_escape_string($link, $_POST['textDesc']);
$textType = mysqli_real_escape_string($link, $_POST['textType']);
$userIDForTable = mysqli_real_escape_string($link, $_SESSION['id']);
我可以在 actions.php else { } 部分中回显语句,因此代码肯定连接到那里,但我真的似乎无法弄清楚原因。我什至将上面的代码链接到同一个数据库中的不同 php 表并让它工作,所以我无法理解为什么这不起作用。我也可以看到控制台中没有错误。任何帮助将不胜感激。