-1

i have been battling with this piece of code for hours without any headway. Can anyone assist me in getting around this please? I’m working on a forum page on my website, with comments and replies to comments functionalities. On click of the Reply button under each comments, a textarea dynamically shows up for reply. The replies are inserted to the database with a reply id and the original comment id (the id generated while posting the original comment been replied to). My challenge now is that replies to any of the comments on the forum seem to reference only the id of the latest comment (perhaps because the reply forms are dynamically generated). Thus in my database, they are having an Id of the latest comment. This in effect means on fetching, the replies will all queue up under the latest comment.What i need is a way of referencing the id of the comment been replied to. Here’s my php code:

<?php
        require("includes/conn.php");
        $stmt=$conn->prepare("SELECT post_id, user, topic, post, time FROM post_tb ORDER BY time DESC");
            $stmt->execute();
            $result = $stmt->get_result();
            $num_of_rows = $result->num_rows;
            if ($num_of_rows > 0){
                while ($row = $result->fetch_assoc()){
                    $post_id = $row['post_id'];
                    $user = $row['user'];
                    $topic = $row['topic'];
                    $post = $row['post'];
                    $time = $row['time'];
                    $time = date('M dS, Y g:i A', strtotime($time));
                    echo '<div>
                            <div>
                                <h5><strong>'.$user.'</strong></h5><h6>'.$time.'</h6>
                                <h5><strong>'.ucfirst($topic).'</strong></h5>
                                <p data-id="'.$post_id.'">'.$post.'</p>
                            </div>      
                            <div>
                                <button type="button" class="btn btn-primary rep" id="but_rep" data-id="'.$post_id.'">Reply</button>
                            </div>
                            <form id="comment_reply" data-id="'.$post_id.'" method="post" action="">
                                <input type="text" class="hidden" value="'.$post_id.'" id="post_id">
                                <input type="text" class="hidden" value="'.$user.'" id="user">
                                <textarea class="form-control" rows="3" name="post_rep" id="post_rep"></textarea>
                                <button type="submit" class="btn btn-primary" id="post_rep_sub">Submit</button>
                            </form>
                        <div/>';
                    }
                }
    ?>

And my Ajax/jquery here:

$("form#comment_reply").hide();//Comment reply form hidden at page load
//To hide reply button and show the reply form
$(document).on('click', 'button.rep', function(e){
    e.preventDefault();
    var closestDiv = $(this).closest('div');
    var closestForm = $(closestDiv).next('form#comment_reply');
    $(closestDiv).fadeOut();
    $(closestForm).fadeIn();
});
//To process comment reply
$(document).on("click", "form button#post_rep_sub", function(e){
        e.preventDefault();
    var reply = $("form textarea#post_rep").val();
    var name = $("input#user").val();
    var post_id = $("input#post_id").val();
    if (reply != ''){
        $.post('insert_post_reply.php', {'reply':reply, 'name':name, 'post_id':post_id}, function(data){
            if (data = 'yes'){
               $("form textarea#post_rep").val("");
               fetchCommentReply();
            }
        });
    }else{
        return false;
    }
});
banky
  • 838
  • 2
  • 13
  • 26
  • What does fetchCommentReply(); do? – mplungjan Jun 03 '17 at 10:43
  • @mplungjan.thanks.It's a function that fetches the replies to comments based on the id of the comment been replied to. the issue is not with it as even an alert(post_id) keeps alerting the id of the latest comment. – banky Jun 03 '17 at 10:48
  • Please post a [mcve] - If you think it is a PHP issue then I cannot see it. If it is a jQuery issue only, then please post the HTML rendered by the PHP using the `<>` button so we can see if you have a closure issue - which is the most likely – mplungjan Jun 03 '17 at 16:15
  • Is this a JS problem, or a PHP problem? – Nico Haase Aug 17 '23 at 15:47

2 Answers2

0

I think the issue is in the click-handler "form button#post_rep_sub".

You read the post_id with this statement: var post_id = $("input#post_id").val(); But this always returns the last post_id no matter which button was pressed.

To validate my point you can add this and observe the javascript-console:

var test1 = $("input#post_id");
var test2 = $("input#post_id").length;
console.log(test2);

If you see a number >1, then you know to fix click-handler "form button#post_rep_sub".

Aedvald Tseh
  • 1,757
  • 16
  • 31
  • Thanks @Tseh. Let me modify my var post_id = $("input.hidden").val() to be clear, the value of the comment id declared in the hidden input field. Coming back to your suggestion, a console.log test returned 0. – banky Jun 03 '17 at 11:04
  • @Tseh..i meant to say the console.log test returned the id of the latest comment still – banky Jun 03 '17 at 11:09
  • Could you provide the html, which is generated by the PHP-script ? This would allow me to reproduce your issue. You can do this in Google Chrome by right clicking and then in t he menu choosing "Inspect". – Aedvald Tseh Jun 03 '17 at 11:23
  • Thanks @Tseh. In my original question, i posted a php code which generates the form html for the comment and replies. i used Jquery to hide the reply form at page load, and then upon `click' event of the reply button, the reply form fades in. Now, wrongly,all replies to any of the comments get inserted with the comment id of the latest comment. Since my fetchCommentReply sql fetches the replies WHERE commentId = id of the comment been replied to, all the replies are fetched and displayed under the latest comment, instead of been under individual comments been replied.i hope it made sense? – banky Jun 03 '17 at 11:42
  • @banky: Does this mean that your issue is resolved ? If so, please upvote my answer. It looks like my answer was helpful for you! – Aedvald Tseh Jun 03 '17 at 13:32
  • @Tseh..my issue hasn't been resolved.i only tried throwing more light on it in my last comment. – banky Jun 03 '17 at 13:39
  • @mplungjan, if u want to help and my explanation isn't detailed enough pls ask me what you want to know and I'd give details.Thanks – banky Jun 03 '17 at 13:39
0

The main issue is that your php-code generates html-elements (e.g. button) several times with the same id! And then jquery only attaches itself to the first button. This was already explained with an example here:

How jQuery works when there are multiple elements with the same "id"?

Solution: replace id with name-attribute!


According to the HTML specification, the id attribute MUST be unique on a page (it's not a criteria web designers/developers just invented)

Is using the same id multiple times on a page bad practice even when I am not parsing through the page?


Let's take a closer look at what your php generates. You have multiple elements with same id, for example the button with id="but_rep" is generated many times. Please note your are only allowed to use an id one time only in an html-file! And therefore you cannot assume that jquery reliably attaches an event-handler using an id!

                     <div>
                        <div>
                            <h5><strong>user 1</strong></h5><h6>'.$time.'</h6>
                            <h5><strong>topic 1</strong></h5>
                            <p data-id="101">post text1</p>
                        </div>      
                        <div>
                            <button type="button" class="btxtn btn-primary rep" id="but_rep" data-id="101">Reply</button>
                        </div>
                        <form id="comment_reply" data-id="101" method="post" action="">
                            <input type="text" class="hidden" value="101" id="post_id">
                            <input type="text" class="hidden" value="user 1" id="user">
                            <textarea class="form-control" rows="3" name="post_rep" id="post_rep"></textarea>
                            <button type="submit" class="btn btn-primary" id="post_rep_sub">Submit</button>
                        </form>
                    <div/> 
                    <div>
                        <div>
                            <h5><strong>user 2</strong></h5><h6>'.$time.'</h6>
                            <h5><strong>topic 2</strong></h5>
                            <p data-id="102">post text2</p>
                        </div>      
                        <div>
                            <button type="button" class="btxtn btn-primary rep" id="but_rep" data-id="102">Reply</button>
                        </div>
                        <form id="comment_reply" data-id="102" method="post" action="">
                            <input type="text" class="hidden" value="102" id="post_id">
                            <input type="text" class="hidden" value="user 2" id="user">
                            <textarea class="form-control" rows="3" name="post_rep" id="post_rep"></textarea>
                            <button type="submit" class="btn btn-primary" id="post_rep_sub">Submit</button>
                        </form>
                    <div/> 
Aedvald Tseh
  • 1,757
  • 16
  • 31
  • @Tseh Thanks so much for your assistance again. Now I realize why I keep getting that same id. However, I’m trying to modify my code to generate a reply button with unique name attribute whose value is the id of the comment been replied to, same for the reply textarea form, but I’m having challenges referencing the name attribute in the event handler as it keeps throwing up error: here is what im attempting in jquery: `var post_id = $("input#post_id").val(); $(document).on('click', 'button[name:"+post_id+"]', function(e){ e.preventDefault();alert("yes"); });` – banky Jun 04 '17 at 21:04
  • @banky: It is an honour to help you! Please upvote my anwer. – Aedvald Tseh Jun 04 '17 at 21:08
  • @Tseh Pls im still having challenges referencing the name attribute in the event handler as it keeps throwing up uncaught syntax error at the console. Pls see my last comment – banky Jun 04 '17 at 21:22