Shaikh Mujibur Rahman Shaikh Mujibur Rahman - 2 years ago 115
Ajax Question

How to handle php loop through elements with jquery

I have an HTML form that will return as HTML format with JQuery Ajax after the insertion query is successful.


mysql_query("INSERT INTO comment(comment,post_id,)VALUES('$comment','$post_id')");
<p><?php echo $comment; ?></p>

This is my JQuery code that will send the request and values and return the HTML form after the insertion query succeeds.


// on post comment click
var theCom=$(this).siblings('.the-new-com');
alert('You need to write a comment!');
var post_id=$(this).parents(".post_id").attr("id");
type: "POST",
url: "comment.php",
data: "act=add-com&comment="+theCom.val()+"&id="+post_id,
success: function(html){
$('.the-new-com').hide('fast', function(){

This my form. It's running within a loop of posts submitted by the user every time.

<form action="" method="POST" class="post_id" id="<?php echo $post_id; ?>">

<span>Write a comment ...</span>
<div class="new-comment-line"></div><----here is a line before the comment initiates..--->
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>

And now my question is that my all code works very well except last few lines of JQuery code.


The line of code when my form returns the HTML form from comment.php after the Ajax request has the problem. The form prints every time, in every post, that the user submitted the status.

How should I handle the form? I want my comments to print every time only in the specific post submitted by the user.

Answer Source

Obviously $('.new-comment-line') is a class selector and you are selecting all elements in this class. As you start your function by clicking on a button, I suggest the selection of correct element relative to the clicked button. So immediately after clicking a button, select the correct element:

var correctElement=$(this).siblings('.new-comment-line');

and then add the html to it when needed:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download