As shown from the diagram, I have two tables in my mysql and I would like the system to add and retrieve comment without refreshing the page.
I have three php pages involved in this function and they are 'DB.php', 'comment.php' and 'action.php'
The codes are as shown:
DB.php
<?php
$conn = mysql_connect('localhost','Practical4','1234') or die (mysql_error);
$db=mysql_select_db('Practical4', $conn) or die (mysql_error);
?>
comment.php
<----------------ajax script-------------------->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<-----retrieve hotel id from hotel table-------->
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<---------------post form------------------->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string(trim($_POST['content']));
$name=mysql_real_escape_string(trim($_POST['name']));
mysql_query("insert into comment(content,name) values ('$content','$name')");
$fetch= mysql_query("SELECT content FROM comment order by commentID desc where name = '$name'");
$row=mysql_fetch_array($fetch);
}
?>
<div class="showbox"> <?php echo $row['content']; ?> </div>
when I run this, the page display nothing when I insert the comment, can anyone help me to solve this? Thanks a lot!!
Some changes have been made as follows:
comment.php
<!-- ajax script -->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = 'content='+ textcontent + '&name='+name;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<!-- retrieve hotel id from hotel table -->
<?php
include('DB.php');
$id=$_GET['id'];
$query = mysql_query("select * from hotel where name='$id'");
while($rows=mysql_fetch_array($query)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<!-- post form -->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=$_POST['content'];
$name=$_POST['name'];
mysql_query("insert into comment (content,name) values ('$content','$name')");
echo '<div class="showbox">'.$content.'</div>';
}
?>
Reasons why your code failed:
name not added in dataString causing name not sent in post
some mysql errors
Related
I am trying to submit a form using ajax. However, it is not showing the message that the code is wrong. I push errors the same way on the entire website so that part works.
This is my code:
<script type="text/javascript" src="jquery.js"></script>
<div id="showerrors"></div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#showerrors').load('errors2.php')
}, 1000);
});
</script>
<form id="formoid" method="post" action="data/newpass.php">
<div class="row2">
<input type="email" class="form-control2" placeholder="email adres" aria-describedby="basic-addon1" name="email" required>
</div>
<div class="row2">
<input type="text" class="form-control2 pull-left" placeholder="Enter code" aria-describedby="basic-addon1" name="captcha" style="width: 70%;" required>
<div class="capbg1">
<input type="text" class="disable1b pull-right" value="<?php echo $capcode3;?>" name="captcha" style="width: 29%;" disabled>
</div>
</div>
<div class="row2"></div>
<div class="row2">
<button type="submit" class="w3-black pull-left" name="req_new_pw">Request new password</button>
</div>
</form>
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : { email: $('#email').val(), captcha: $('#captcha').val() },
});
});
</script>
// newpass.php - action in the form
<?php
error_reporting(E_ALL);
session_start();
ob_start();
$db = mysqli_connect(***);
if (isset($_POST['req_new_pw']))
{
$captcha = mysqli_real_escape_string($db, $_POST['captcha']);
$email = mysqli_real_escape_string($db, $_POST['email']);
if(isset($_SESSION['capcode3']))
{
if($_SESSION['capcode3'] != $captcha)
{
array_push($errors, "- Code is incorrect.");
}
}
}
?>
//errors.php
<?php if (count($errors) > 0) : ?>
<div class="isa_error">
<i class="fa fa-times-circle"></i>
<b>Oops..</b><br>
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
//errors2.php - display errors above form
<?php
include('errors.php');
if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</div>
</h3>
</div>
<?php endif ?>
When i submit the form, nothing happens.
What am i doing wrong?
You don't send $_POST['req_new_pw'] and you are asking if it's set.
You can use serialize() to send all form element by post:
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : $('#formoid').serialize(),
});
});
</script>
Make sure you are setting $_SESSION['capcode3'] either.
This works like a charm:
$("#formoid").submit(function(event) {
event.preventDefault();
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data
});
});
My ajax return results are four values.I want assign these values to four input value.Here my ajax code:
$.ajax({
type:"POST",
url:"modify_cbndtb.php",
data: {cabinetNum:id},
success:function (res)
{
}
});
modify_cbndtb.php code:
if(isset($_POST['cabinetNum']))
{
$q=$_POST["cabinetNum"];
$sql="select num1,num2,num3,num4 from hpc WHERE sysid= '".$q."';";
$sel = $conn->query($sql);
}
My html code:
<div id="content" class="content">
1U:<input type="text" id="1U" value="">11U:<input type="text" id="11U" value=""><br />
2U:<input type="text" id="2U" value="">12U:<input type="text" id="12U" value=""><br />
</div>
1U.value should be num1. 2U.value should be num2. 3U.value should be num3. 4U.value should be num4. But I don't know how to realize. Who can help me?
I think you can try this
modify_cbndtb.php
if(isset($_POST['cabinetNum']))
{
$q=$_POST["cabinetNum"];
$sql="select num1,num2,num3,num4 from hpc WHERE sysid= '".$q."';";
$sel = $conn->query($sql);
$arr = $sel->fetch(PDO::FETCH_ASSOC);
$data = json_encode($arr);
echo $data;
}
and AJAX
client file
$.ajax({
type:"POST",
url:"modify_cbndtb.php",
data: {cabinetNum:id},
success:function (data) {
$('#1U').val(data[0].num1);
$('#11U').val(data[0].num2);
$('#2U').val(data[0].num3);
$('#12U').val(data[0].num4);
}
});
I hope it help you
Try this
modify_cbndtb.php
<?php
if(isset($_POST['action']))
{
$q=$_POST["cabinetNum"];
$sql="select num1,num2,num3,num4 from hpc WHERE sysid= '".$q."';";
$sel = $conn->query($sql);
while($row = $sel->fetch_assoc()){
echo $row['num1'].",".$row['num2'].",".$row['num3'].",".$row['num4'];
}
}
?>
your form
<script type="text/javascript" src="testing/jquery-3.2.1.js"></script>
<form id="form">
<input type="submit" name="submit" id="submit">
<input type="hidden" id="cabinetNum" name="cabinetNum" value="1">
</form>
<div id="content" class="content">
1U:<input type="text" id="1U" value="">3U:<input type="text" id="3U" value=""><br />
2U:<input type="text" id="2U" value="">4U:<input type="text" id="4U" value=""><br />
</div>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','#submit',function(e){
e.preventDefault();
var dataen = $("#form").serialize() + "&action";
$.ajax({
type:"POST",
url:"modify_cbndtb.php",
data: dataen,
success:function (data) {
$(function(){
var valData = data;
var valNew=valData.split(',');
for (i = 0; i < valNew.length; i++) {
valNew[i] = valNew[i];
$('#'+(i + 1)+'U').val(valNew[i]);
}
});
}
});
});
});
</script>
I'm still in a learning shift when it comes to Ajax. I made a script that sends data to a database and it works. The data inserts. Now my question is how can I display the data on the page?
display.php
<div class='displayMessage' style='height: 540px; padding:5%; overflow-x:hidden;'>
<?php
$chatmsgQ="SELECT * FROM ve_chat c
WHERE c.isActive='1' AND c.fromUserId='$loginid_session'
OR c.toUserId='$loginid_session'";
$chatmsgresult= mysqli_query($db,$chatmsgQ);
while($chatmsg= mysqli_fetch_array($chatmsgresult)){?>
<?php if($chatmsg['fromUserId']==$loginid_session):?>
<!-- user one -->
<p class='bubble pull-left'><?=$chatmsg['message'];?></p>
<?php elseif($chatmsg['fromUserId']!=$loginid_session):?>
<!-- user two-->
<p class='bubbleother pull-right'><?=$chatmsg['message'];?></p>
<?php endif;?>
<?php } ;?>
</div>
<!-- write message-->
<form id="chatForm" method='post' action='chat.php'>
<textarea id='chatMessage' name='chatMessage' placeholder="Type your message here... " value=''></textarea>
<button id='buttons' type="submit" name='sendChat' class="btn btn-default">Send</button>
<input type='hidden' id='fromUserId' name='fromUserId' value='<?=$loginid_session;?>'>
<input type='hidden' id='toUserId' name='toUserId' value='<?=$touserid;?>'>
</form>
js script
<script>
$(document).ready(function(){
$("#buttons").click(function(){
var fromuserid = $("#fromUserId").val();
var touserid = $("#toUserId").val();
var chatMessage = $("#chatMessage").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'fromUserId='+ fromuserid + '&toUserId='+ touserid + '&chatMessage='+ chatMessage;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
cache: false,
success: function(result){
//what do I put here exactly?
}
});
return false;
});
});
</script>
chat.php
//get variables
$chatMessage= $_POST['chatMessage'];
$fromUserId= $_POST['fromUserId'];
$toUserId= $_POST['toUserId'];
$chatStatus='1';
//insert in ve_articles_comments
$startChatQ = $db->prepare("INSERT INTO ve_chat (fromUserId,toUserId,message,isActive) VALUES (?,?,?,?)");
$startChatQ ->bind_param("iisi",$fromUserId,$toUserId,$chatMessage,$chatStatus);
$startChatQ ->execute() or die(mysqli_error($db));
if($startChatQ ){
// echo "Data Submitted succesfully";
$_SESSION['success']='<h4 style="text-align: center;" class="alert alert-success alert-dismissable" >×Your chat request was sent with success.</h4>';
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
$startChatQ ->close();
$db->close();
Alright so this works for me:
display.php
<div class='displayMessage' style='height: 540px; padding:5%; overflow-x:hidden;'>
<?php
$chatmsgQ="SELECT * FROM ve_chat c
WHERE c.isActive='1' AND c.fromUserId='$loginid_session'
OR c.toUserId='$loginid_session'";
$chatmsgresult= mysqli_query($db,$chatmsgQ);
while($chatmsg= mysqli_fetch_array($chatmsgresult)){?>
<?php if($chatmsg['fromUserId']==$loginid_session):?>
<!-- user one -->
<p class='bubble pull-left'><?=$chatmsg['message'];?></p>
<?php elseif($chatmsg['fromUserId']!=$loginid_session):?>
<!-- user two-->
<p class='bubbleother pull-right'><?=$chatmsg['message'];?></p>
<?php endif;?>
<?php } ;?>
</div>
<!-- write message-->
<form id="chatForm" method='post' action='chat.php'>
<textarea id='chatMessage' name='chatMessage' placeholder="Type your message here... " value=''></textarea>
<button id='buttons' type="submit" name='sendChat' class="btn btn-default">Send</button>
<input type='hidden' id='fromUserId' name='fromUserId' value='<?=$loginid_session;?>'>
<input type='hidden' id='toUserId' name='toUserId' value='<?=$touserid;?>'>
</form>
jQuery
$(document).ready(function(){
$("#buttons").click(function(){
var fromuserid = $("#fromUserId").val();
var touserid = $("#toUserId").val();
var chatMessage = $("#chatMessage").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'fromUserId='+ fromuserid + '&toUserId='+ touserid + '&chatMessage='+ chatMessage;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
cache: false,
success: function(response){
$("#displayMessage").html(response);
}
});
return false;
});
});
chat.php
//get variables
$chatMessage= $_POST['chatMessage'];
$fromUserId= $_POST['fromUserId'];
$toUserId= $_POST['toUserId'];
$chatStatus='1';
$loginid_session=$_POST['fromUserId'];
//insert in ve_articles_comments
$startChatQ = $db->prepare("INSERT INTO ve_chat (fromUserId,toUserId,message,isActive) VALUES (?,?,?,?)");
$startChatQ ->bind_param("iisi",$fromUserId,$toUserId,$chatMessage,$chatStatus);
$startChatQ ->execute() or die(mysqli_error($db));
if($startChatQ ){
// echo "Data Submitted succesfully";
$chatmsgQ="SELECT * FROM ve_chat c WHERE c.isActive='1' AND (c.fromUserId='$loginid_session' OR c.toUserId='$loginid_session')";
$chatmsgresult= mysqli_query($db,$chatmsgQ);
while($chatmsg= mysqli_fetch_array($chatmsgresult)){
if($chatmsg['fromUserId']==$loginid_session){
echo " <p class='bubble pull-left'>" .$chatmsg['message'] . "</p> ";
}
elseif($chatmsg['fromUserId']!=$loginid_session){
echo " <p class='bubbleother pull-right'>" . $chatmsg['message'] . "</p> ";
} }
}
$startChatQ ->close();
$db->close();
I have tried many ways to build a commenting system for my website with php jquery,ajax but problem with inserting comments in data base what is the problem with my code
Html
<div id="comments" class="cmt">
<form method="post" >
<textarea class="textinput"id="comment" rows="5" name="comments" placeholder="Comment Here......"></textarea><br>
<button type="button" id="comq"name="compost" class="butn2" >post comment</button>
</form>
</div>
Jquery and ajax
$(document).ready(function()
{
$("#comq").click(function() {
var comment=$("#comment").val();
$.ajax({
cache:false,
type:"post",
url:"pnf.php",
data:{comments:comment},
success:function(data)
{
$('.cmt').html(data);
}
});
});
});
Php (pnf.php)
if(isset($_POST["compost"])){
$comment=$_POST['comments'];
{
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
}
if($stmt)
{
echo "hello world";
}
}
Try this:
HTML
<div id="comments" class="cmt">
<textarea class="textinput" id="comment" rows="5" name="comments" placeholder="Comment Here......"></textarea><br>
<button type="button" id="comq"name="compost" class="butn2" >post comment</button>
</div>
For PHP:
if(isset($_POST["comments"])){
$comment = $_POST['comments'];
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set
uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
if($stmt)
{
echo "hello world";
}
}
You have an error in type:
if(isset($_POST["compost"])){
$comment=$_POST['comments'];
I mean $_POST["compost"] and $_POST["compost"] are different variables
first just isset the $_POST Comment to check if you have you comment value
if(isset($_POST["comments"])){
$comment=$_POST['comments'];
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,qid= '".$qid."' ");
if($stmt)
{
return true;
}
}
second you can id to your form to reset after the ajax call success
<form id="myForm"> // add ID to your form
success:function(data){
if(data == true){
$('#myForm')[0].reset(); //to reset your form after success
$('.cmt').html(data);
} else{
//do the error msg
}
}
I'm sharing working code snippets.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" ></script>
</head>
<body>
<div id="comments" class="cmt">
<form method="post" onsubmit="submitComment(); return false;">
<textarea class="textinput" id="comment" rows="5" name="comments" placeholder="Comment Here......"></textarea><br>
<button type="submit" id="comq"name="compost" class="butn2" >post comment</button>
</form>
<p id="message" ></p>
</div>
<script>
function submitComment() {
var comment = $("#comment").val();
$.ajax({
cache: false,
type: "post",
url: "pnf.php",
data:{
comment:comment
},
success:function(data) {
$('#message').html(data);
}
});
return false;
}
</script>
</body>
</html>
and PHP script
<?php
$connection = mysqli_connect("localhost","my_user","my_password","my_db");
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST["comment"])) {
$comment = mysqli_real_escape_string($connection, $_POST['comment']);
$sql = "INSERT INTO `comments` (`comment`) VALUES ('".$comment."')";
$res = mysqli_query($connection, $sql);
if($res) {
echo "success";
} else {
echo "error";
}
}
So i am haveing this page where it is displaying articles andunderneet each article it will have a textarea asking allowing the user to insert a comment.I did the AJAX and it works fine.Some of the validation works fine aswell(Meaning that if the textarea is left empty it will not submit the comment and display an error).The way i am doing this validation is with the ID.So i have multi forms with the same ID.For the commets to be submited it works fine but the validtion doesnt work when i go on a second form for exmaple it only works for the first form
AJAX code
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('#comment');
if (comment.val().length > 1)
{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Hello");
}
});
});
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" >
<label>New Comment</label>
<textarea id="comment" name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Again the problem being is the first form works fine but the second one and onwaord dont work properly
try this:
var comment = $('.comment',form);
instead of
var comment = $('#comment');
That way you're targeting the textarea belonging to the form you're validating
ps.
remove the id's from the elements or make them unique with php, all element id's should be unique