I have created a comment-reply system usign php and jquery. My code includes a function for comments and then using jquery I am trying to get comments_id which is the id for each comment and the reply and save it a table called comments_reply. My only problem is that I cannot get comments_id, but I can successfuly get reply and store it in the comments_reply table. Any idea why my code cannot get comments_id to store it?
This is my function in php including jquery:
<?php
<script>
$(document).ready(function(){
$('.reply').keyup(function(e){
if(e.keyCode == 13){
var comments_id = $(this).attr('comments_id');
var reply = $(this).val();
$.post('reply.php', {comments_id:comments_id, reply:reply});
$('.reply').val('');
}
});
});
</script>
function getComments(){
$comments = "";
$sql = mysql_query("SELECT * FROM comments ORDER BY comment_date DESC ") or die (mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = " <div class='each_comment'> There are no comments ...</div> ";
}
else
{
while ($row= mysql_fetch_assoc($sql)){
$comments .= "User Says : <div class='each_comment'> ".$row['comment_date']."".$row['comment']."
<input type='text' class='reply' comments_id='<?php ".$row['comments_id']." ?>' />
</div> ";
}
}
return $comments;
}
?>
And this is my page: reply.php
<?php
$comments_id = $_POST['comments_id'];
$reply = $_POST['reply'];
mysql_query("INSERT INTO comments_reply VALUES ('', '$comments_id', '$reply') ");
?>
to prevent any confusion between your value and propery name (being exactly the same) when submitting to the server you should add quotes to the name.
$('.reply').keyup(function(e){
if(e.keyCode == 13){
var comments_id = $(this).attr('comments_id');
var reply = $(this).val();
$.post('reply.php', {"comments_id":comments_id, "reply":reply});
$('.reply').val('');
}
});
that may even fix your issue
EDIT
I would also change your custom html attribute names like so:
change comments_id
to data-comment-id
and reply
to data-reply
for the sake of convention and possibly usefull html5 support and don't forget to update all usages (in html and javscript code).
I have also noticed your sql code VALUES ('', '$comments_id', '$reply')
shows that you are inserting a blank value to the first column in the table is there a reason for this?
EDIT2
For when people look at what the answer was instead of reading the comments of this answer I will put it here:
replace
<input type='text' class='reply' comments_id='<?php ".$row['comments_id']." ?>' />
with
<input type='text' class='reply' comments_id='{$row['comments_id']}' />
or the id will include unwanted characters.