【问题标题】:PHP JS ajax submit form on page load and also trigger once another function succeededPHP JS ajax 在页面加载时提交表单,并在另一个函数成功后触发
【发布时间】:2019-08-14 07:06:14
【问题描述】:

我有 2 个表单,每个表单都有一个 JS 脚本,其中一个在单击提交按钮后加载一些 cmets,另一个脚本提交评论。

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>title</title>
</head>

<body>

<?php 

$conn = mysqli_connect('dbserver', 'dbuser', 'dbpw', 'dbname') or die("Connection failed: " . mysqli_connect_error());
$conn->query("SET NAMES 'utf8'");
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }  

$sql = "SELECT * FROM table_name ORDER BY date ASC";  

$rs_result = mysqli_query($conn, $sql);

//the following part will echo multiple individual forms, depending on the table content.
while ($row = mysqli_fetch_assoc($rs_result)) {

    echo '
        <form action="load_comments.php" method="POST" id="form_' . $row["id"] . '" class="load_comments_form">

            <div id="result_comments_form_' . $row["id"] . '">
            <!--load all comments here-->
            </div>

            <input type="hidden" name="identifier" value="' . $row["identifier"] . '">
            <input type="hidden" name="translation_language" value="' . $row["language"] . '">

            <input type="submit" name="" value="Load / refresh comments" class="load-comments">
        </form>



        <form action="save_comment.php" method="POST" id="save_comment_form_' . $row["id"] . '" class="comment_form">
            <textarea rows="4" name="comment_content" class="textarea-comment"></textarea>
            <input type="hidden" name="username" value="' . $row["username"] . '">
            <input type="hidden" name="identifier" value="' . $row["identifier"] . '">
            <input type="hidden" name="translation_language" value="' . $row["language"] . '">

            <input type="submit" name="" value="Send" class="submit-comment">
        </form>
    ';  
}

?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<!--Script 1: Load all comments-->
<script>
$(document).ready(function() {
    $(".form").submit(function() {
        // Getting the form ID
        var  formID = $(this).attr('id');
        var formDetails = $('#'+formID);
        $.ajax({
            type: "POST",
            url: 'load_comments.php',
            data: formDetails.serialize(),
            success: function (data) {  
                // Inserting html into the result div
                $('#result_comments_'+formID).html(data);
            },
            error: function(jqXHR, text, error){
            // Displaying if there are any errors
                $('#result_comments_'+formID).html(error);           
        }

    });
        return false;
    });

});
</script>


<!--Script 2: Save comment-->
<script>
$(document).ready(function() {
    $(".save_comment_form").submit(function() {
        $('<div class="changes-saved_comment">&#10003; Comment sent.<br>Admin has been notified.</div>').insertAfter(this).fadeOut(6000);
        // Getting the form ID
        var  formID = $(this).attr('id');
        var formDetails = $('#'+formID);
        $.ajax({
            type: "POST",
            url: 'save_comment.php',
            data: formDetails.serialize(),
            success: function (data) {  
                // Inserting html into the result div
            },
            error: function(jqXHR, text, error){
            // Displaying if there are any errors
        }

    });
        $('.textarea-comment').val(''); //clean textarea
        return false;
    });
});
</script>

</body>
</html>

这是当前状态的快速演示视频:

https://streamable.com/n94sa

正如在视频中看到的,我必须单击第一个表单/脚本的提交按钮才能加载 cmets。虽然,提交按钮应该保留在那里以便按需触发,但它也应该在页面加载时触发一次。

第二个脚本提交了一条新评论。 从视频中可以看出,提交后cmets不会自动刷新。 所以我需要第二个脚本,一旦成功,触发第一个表单/脚本的提交。

请记住,每个页面有多个表单,这些表单是使用 row["id"] 动态创建的,我在 formDetails.serialize() 的帮助下将动态创建的参数传递给两个 .php 文件。

谢谢。

【问题讨论】:

  • 如果我知道您想在保存新评论后重新加载所有 cmets?
  • 是的,没错。

标签: php jquery ajax parameter-passing submit


【解决方案1】:

在保存注释脚本调用Load all cmets form submit在ajax成功

    <!--Script 2: Save comment-->
<script>
$(document).ready(function() {
    $(".save_comment_form").submit(function() {
        $('<div class="changes-saved_comment">&#10003; Comment sent.<br>Admin has been notified.</div>').insertAfter(this).fadeOut(6000);
        // Getting the form ID
        var  formID = $(this).attr('id');
        var formDetails = $('#'+formID);
        $.ajax({
            type: "POST",
            url: 'save_comment.php',
            data: formDetails.serialize(),
            success: function (data) {
                $(".form").submit();//call this here in the success function
                // Inserting html into the result div
            },
            error: function(jqXHR, text, error){
            // Displaying if there are any errors
        }

    });
        $('.textarea-comment').val(''); //clean textarea
        return false;
    });
});
</script>

更新

步骤: 1. 要添加一个表单,您首先需要为您的 result_cmets_form_SOMEID div 添加一个父元素 div

echo '
    <form action="load_comments.php" method="POST" id="form_' . $row["id"] . '" class="load_comments_form">
        <div class="parent_div">
          <div id="result_comments_form_' . $row["id"] . '">
           <!--load all comments here-->
          </div>
        </div>

        <input type="hidden" name="identifier" value="' . $row["identifier"] . '">
        <input type="hidden" name="translation_language" value="' . $row["language"] . '">

        <input type="submit" name="" value="Load / refresh comments" class="load-comments">
    </form>'

步骤: 2. 将最新评论保存到save_comment.php 后,需要将最新评论的id 保存在一个变量中。

$last_id = $conn->insert_id;

然后,您可以针对此$last_id 获取具有idcomment 的最后插入记录。之后,你需要像这样以json格式回显它

echo json_encode($latest_record);

然后你会在你的jquery ajax成功函数中收到这个json数组,你可以在控制台打印出来进行验证

步骤:3. 您需要像这样在 jquery 代码中解码该 json 字符串

var obj = jQuery.parseJSON( data );

现在您可以像这样在 ajax 成功中将这条新记录附加到父 div 中。

 $( ".parent_div" ).append('<div id="result_comments_form_' + data.id + '">' + data.comment + '</div>');

【讨论】:

  • 还不错。实际上,我希望有一种方法可以重新加载我提交评论的实例的特定 div。相反,您的解决方案会更新页面上的所有评论 div。但是 nvm,这也是可以接受的。关于如何在初始页面加载时提交的任何建议?这次确实是页面上的所有实例。
  • 为此,您可以在ajax成功中使用jQuery append()函数在新div中附加注释
  • 你能解释得更详细一点吗?也许您可以将其添加到您的答案中。那会很酷。
  • 你能准确定义你在哪里填充你的 cmets
  • 查看第一个表单之前的“while”循环。它将创建大约 10 个表单实例,每个实例都有一个单独的 id。 cmets 应该在
    的每个实例的页面加载时加载。目前这只能通过手动提交来实现(参见初始帖子中的视频)。但是我需要在页面加载时已经加载表单的每个实例的所有 cmets,而不必手动触发它。
【解决方案2】:

出于性能目的,您只需像这样更新 save-comment-form,只需提交此评论所属的兄弟表单即可

<form action="save_comment.php" method="POST" data-row-id="' . $row["id"] . '" id="save_comment_form_' . $row["id"] . '" class="comment_form">
    <textarea rows="4" name="comment_content" class="textarea-comment"></textarea>
    <input type="hidden" name="username" value="' . $row["username"] . '">
    <input type="hidden" name="identifier" value="' . $row["identifier"] . '">
    <input type="hidden" name="translation_language" value="' . $row["language"] . '">

    <input type="submit" name="" value="Send" class="submit-comment">
</form>

然后像这样更新上面的答案

<!--Script 2: Save comment-->
<script>
$(document).ready(function() {
    $(".comment_form").submit(function() {
        $('<div class="changes-saved_comment">&#10003; Comment sent.<br>Admin has been notified.</div>').insertAfter(this).fadeOut(6000);
        // Getting the form ID
        var  formID = $(this).attr('id');
        var formDetails = $('#'+formID);
        var rowId = $(this).data('rowId');
        $.ajax({
            type: "POST",
            url: $(this).attr('id'),
            data: formDetails.serialize(),
            success: function (data) {
                $("#form_" + rowId).submit();//call this here in the success function
                // Inserting html into the result div
            },
            error: function(jqXHR, text, error){
            // Displaying if there are any errors
            }

        });
        $(this).find('.textarea-comment').val('Hello');  //clean the related textarea
        return false;
    });
});
</script>

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多