PHP JS ajax在页面加载时提交表单,并且一旦另一个函数成功也会触发

问题描述 投票:0回答:2

我有两个表单,每个表单都有一个JS脚本,一旦点击提交按钮就加载一些注释,另一个脚本提交注释。

<!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

如目前视频中所示,我必须单击第一个表单/脚本的提交按钮才能加载注释。但是,提交按钮应该保留在那里以便按需触发,但它也应该在页面加载时触发一次。

第二个脚本提交新评论。如视频中所示,评论在提交后不会自动刷新。所以我需要第二个脚本,一旦成功,就会触发第一个表单/脚本的提交。

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

谢谢。

php jquery ajax parameter-passing submit
2个回答
1
投票

在保存注释脚本中,调用在ajax成功中加载所有注释form submit

    <!--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_comments_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;

然后你可以获取最后插入的记录有idcomment对这个$last_id。之后,你需要像这样以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>');

0
投票

出于性能目的,您只需要提交此注释所属的兄弟表单,方法是更新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>
© www.soinside.com 2019 - 2024. All rights reserved.