php 如何使用 AJAX 插入行

k7fdbhmy  于 2023-02-18  发布在  PHP
关注(0)|答案(2)|浏览(163)

我正在创建一个博客文章的页面,我有一些麻烦,让我的'喜欢'(心)功能使用AJAX工作。
它需要提交时,心脏被点击,这应该提交一个新的行到我的PHP数据库没有页面刷新,但表单提交是不工作/张贴。
这是我第一次使用AJAX提交表单,所以很抱歉,如果我是一个新手。
我的PHP表有5列-ID,内容,用户ID,用户名和日期.

$(document).ready(function() {
  $("#heart").click(function() {
    if ($("#heart").hasClass("liked")) {
      $("#heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
      $("#heart").removeClass("liked");
    } else {
      $("#heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
      $("#heart").addClass("liked");
      $("form#myform").submit(function(event) {
        event.preventDefault();
        var title = $("#title").val();
        var user = $("#user").val();
        var userID = $("#userID").val();
        var dte = $("#dte").val();

        $.ajax({
            type: "POST",
            url: "../PHP/user_functions.php",
            data: "title=" + content + "&user=" + user + "&dte=" + dte + "&userID=" + userID,
            success: function(){alert('success');}
        });
    });
    }
  });
});
.fa-heart-o {
  font-size:24px;
  color:black;
  cursor: pointer;
}

.fa-heart {
  font-size:24px;
  color: red;
  cursor: pointer;
}

.ggg{
  display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">



<form id="myform" action="../PHP/user_functions.php" method="post">

    <span class="" id="heart"><i class="fa fa-heart-o" aria-hidden="true"></i></span>

    <input type="hidden" id="title" value="How To Guide Title Example" name="content">
    <input type="hidden" id="user" value="TestBot" name="username">
    <input type="hidden" id="userID" value="<?php echo $userID ?>" name="sessionID">
    <input type="hidden" id="dte" value="<?php echo date('Y/m/d H:i:s'); ?>" name="date">

    <input class="ggg" type="submit" id="submitButton" name="submitButton" value="Submit">

</form>

和我的PHP页面。

<?php
if (isset($_POST['submitButton'])) {

$username = $_POST['username'];
$userID = $_POST['userID'];
$date = $_POST['date'];
$content = $_POST['content'];

$sql = 'INSERT INTO `likes-blog` (username, userID, date, content) VALUES (:username, :userID, :date, :content)';
$stmt = $dbh->prepare($sql);
                                                              
$stmt->execute(['username' => $username, 'userID' => $userID, 'date' => $date, 'content' => $content]);

?>
<?php
}
?>
l2osamch

l2osamch1#

在您的后端/PHP文件中,将其视为POST数据总是被传递到其中。
想想看:当$_ POST ['submitButton']被传递到页面时,你只需要运行控制数据发送到数据库的代码。当你把数据发送到PHP文件时,它什么也不做,因为你告诉它只有当$_ POST ['submitButton']被设置(有一个值)时才运行该代码。
其次,我想提一下,在ajax中,像这样构造POST数据要容易得多,并且也清理了success函数以使其看起来更好一些;你也可以传递一个响应,就像我在这里展示的,PHP文件会在出错的情况下返回,或者你可以让你的PHP文件返回一个自定义的字符串和一个成功消息:

$.ajax({
    type: "POST",
    url: "../PHP/user_functions.php",
    data: {
        title: content,
        user: user,
        dte: dte,
        userID: userID
    },
    success: function(response) {
        alert(response);
    }
})

我还肯定会研究MySQLi预准备语句,并研究如何更好地防止SQL注入。
看看这些PHP函数和如何使用它们,我已经写了一个非常基本的例子,你可以使用,但你也可以改变它,以适应您的需要,只是要确保您使用的函数正确:

// Data:
$dataOne = 5; // <-- integer
$dataTwo = "Hello, world" // <-- string
// in the ...bind_param() function, where "is" is located, in order, you'd use i for integer and s for string, there are others but these are the basic ones, you can find more documentation online for this.
// For example if you passed through the $dataTwo variable and then the $dataOne variable, it would be "si" because the variable with string content gets passed first and the variable with an integer passed second.
// For the ? marks in the $sql string, those directly relate to how many values you're going to pass through. In the computer, ? will be translated to each value passed through in the ...bind_param() function, in order, and insert them into the selected table/columns, in order. Basically, the code below will insert $dataOne into the "column1Name" column and will insert $dataTwo into the "column2Name" column in the "tableName" table.

$sql = "INSERT INTO "tableName" ("column1Name", "column2Name") VALUES (?, ?);";
$stmt = mysqli_stmt_init($conn)
    or die("Could not initiate a connection.");
mysqli_stmt_prepare($stmt, $sql)
    or die("Could not prepare SQL statement.");
mysqli_stmt_bind_param($stmt, "is", $dataOne, $dataTwo)
    or die("Could not bind SQL parameters.");
mysqli_stmt_execute($stmt)
    or die("Could not execute SQL sequence.");
mysqli_stmt_close($stmt)
    or die("Could not close SQL connection.");

看起来很复杂,还有很多东西要学,但不要像这里的其他人一样只希望你自己解决,我想我会给你一个例子。我还建议你学习如何清洗你的POST数据一旦你的AJAX发送到你的PHP文件。你也可以使用上述方法安全地删除和更新行/列/值在你的数据库。(如果你实际上并没有插入数据,例如,如果你使用的是delete语句,你可以简单地不使用... bind_param()函数,因为它在这里没有任何作用。
另外,我认为问题的一部分是您还提交了表单本身,我认为甚至没有执行Ajax代码。ajax之所以有用的一部分原因是因为它允许您将POST和GET数据提交到外部处理程序文件(你的PHP/后端代码/文件)而不需要重新加载页面,这有很多其他的好处,只有在某些情况下,你实际上必须提交表单,就像默认情况下不使用ajax一样。从技术上讲,在大多数情况下,如果你使用ajax,你甚至不需要使用表单。(但不是全部)。例如,你可以完全去掉标签,而只是让你的输入保持正常;你可以使用JS来获取值。设置你的提交按钮为type ="button"(如果它被设置为提交,页面将重新加载,这有点违背了目的;type ="button"将不会重新加载页面)。
这里有一个粗略的例子来说明我所说的:
超文本:

<input type="text" id="firstName" name="firstName" placeholder="What's your first name?"/>
<input type="text" id="lastName" name="lastName" placeholder="What's your last name?"/>
<button type="button" id="submit">Submit</button>

和您的JavaScript w/ajax:

$("#submit").on("click", () => {
    // Get the current value of the input textbox:
    let first = document.querySelector("#firstName").value;
    let last = document.querySelector("#lastName").value;

    if (firstName !== null) {
        // Send data to PHP file:
        // Keep in mind when only sending single data values, you can do it like shown here:
        $.ajax({
            type: "POST",
            url: "path to php file here",
            data: {
                firstName: first,
                lastName: last
            }
            success: function(response) {
                // The following is an example of something you can use to error handle. Have the PHP file handle all the errors and simply make the PHP code respond with 1/true if the code was executed correctly, or if there was an issue, have it respond with false/0:
                if (response == 1) {
                    alert("You've successfully submitted the form.");
                } else if (response == 0) {
                    alert("Sorry, there was an error submitting the form.");
                }
            }
        })
    }
})

PHP示例:

<?php
require("path_to_database_connect_file"); // I never recommend creating a connection inside another file, so do something like this instead. Have a separate PHP file where its sole purpose is creating and starting a connection with your database. I used the connection variable as $conn, it seems in your original question you were using $dbh. The variable name doesn't really matter I just prefer $conn.

$data = array_filter($_POST);
$first = $data['firstName'];
$last = $data['lastName'];

$sql = "INSERT INTO names (firstName, lastName) VALUES (?, ?);";
$stmt = mysqli_stmt_init($conn)
    or exit(false);

mysqli_stmt_prepare($stmt, $sql)
    or exit(false);

mysqli_stmt_bind_param($stmt, "ss", $first, $last)
    or exit(false); // Both $first and $last have type "string", so the passthrough right after $stmt in this function is "ss" for string-string. If $last was an integer, it would be "si" for string-integer, in that order. Though, if you don't mind everything in your database being string types, which is usually fine for basic stuff, you can still just use "s" for everything. So if you're passing 5 variables into 5 different table columns, you could just do "sssss" there.

mysqli_stmt_execute($stmt)
    or exit(false);

mysqli_stmt_close($stmt)
    or exit(false);

echo true; // If any of the above code fails, it will return false back to ajax in the response callback and exit the script, ajax will see the returned value of "response" as "0" and you will receive the alert message of "Sorry, there was an error submitting the form.". If everything works smoothly with no errors, this script will echo or "return" true back to ajax, and ajax will read "true" as "1", therefore in the success method as shown above, you should get the alert message: "You've successfully submitted the form."
wmtdaxz3

wmtdaxz32#

试试这个

<script>
$(document).ready(function() {
  $("#heart").click(function() {
    if ($("#heart").hasClass("liked")) {
      $("#heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
      $("#heart").removeClass("liked");
    } else {
      $("#heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
      $("#heart").addClass("liked");
        let title = $("#title").val();
        let user = $("#user").val();
        let userID = $("#userID").val();
        let dte = $("#dte").val();
    //Ajax
                $.ajax({
                url: "../backend.php", //This your backend file PHP
                data: {
                    "title": title,
                    "user" : user,
                    "userID" : userID,
                    "dte" : dte
                },
                dataType: "JSON",
                type: "POST",
                beforeSend: function() {
                 //Function for sweetalert like loading or any
                },
                success: function(data) {
                  //if succes
                  console.log(data);
                },
                complete: function() {
                   //Function while ajax complete
                },
                error: function(data) {
                   //if error
                    console.log("ERROR");
                    console.log(data);
                }
            }); 
    }
  });
});
</script>

相关问题