0

I have 2 forms with each a JS script of which one loads some comments once a submit button is clicked, and the other script submits a comment.

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

Here is a quick demo video of the current state:

https://streamable.com/n94sa

As seen in the video currently I have to click the submit button of the first form / script in order to load the comments. Though, the submit button should remain there for triggering on demand, but it should also trigger once on page load.

The 2nd script submits a new comment. As seen in the video, the comments are not refreshed automatically after submitting. So I need the second script, once succeeded, to trigger the submit of the first form/script.

Please keep in mind that there are multiple forms per page which are dynamically created with row["id"] and I am passing dynamically created parameters to both .php files with the help of formDetails.serialize().

Thank you.

2
  • So if i understand you want to reload all the comments after saving a new comment ? Commented Mar 23, 2019 at 13:45
  • yes that's right. Commented Mar 23, 2019 at 13:51

2 Answers 2

1

In save comment script call Load all comments form submit in the ajax success

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

Update

STEP: 1. For appending a form you first you need to add a parent element div for your result_comments_form_SOMEID 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>'

Step: 2. After saving the latest comment in save_comment.php you need to save the latest comment's id in a variable.

$last_id = $conn->insert_id;

Then you can fetch the last inserted record having id and the comment against this $last_id. After that, you need to echo it in the json format like this

echo json_encode($latest_record);

Then you will receive this json array in your jquery ajax success function and you can print it in the console for verification

Step: 3. You need to decode that json string in your jquery code like this

var obj = jQuery.parseJSON( data );

Now you can append this new record inside parent div in the ajax success like this.

 $( ".parent_div" ).append('<div id="result_comments_form_' + data.id + '">' + data.comment + '</div>');
Sign up to request clarification or add additional context in comments.

12 Comments

It's not bad. Actually I hoped for a way for just reloading the particular div of the instance where I submit the comment. Instead, your solution updates all comment divs on the page. But nvm, this is acceptable too. Any suggestion for how to submit on the initial page load? This time indeed ALL instances on the page.
For this, you can append the comment in the new div with jQuery append() function in the ajax success
Could you please explain that more detailed? Maybe you could add that to your answer. That would be cool.
Can you define that exactly where are you populating your comments
See the "while" loop before the first form. It will create like 10 instances of the forms, each with an individual id. The comments should be loaded on page load in EVERY instance of <div id="result_comments_form_' . $row["id"] . '">. This is currently only possible with a manual submitting (see video in the initial post). But I need all comments of each instance of the form already loaded up on page load, without having to trigger it manually.
|
0

For performance purpose you need to submit only the sibling form for which this comment belongs, by updating the save-comment-form a little bit like this

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

and then update the answer above like this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.