AJAX improvement for validation - javascript

SO i have this piece of AJAX that work as it should be but i want to add some validation to it.I dont want it to send empty information.The AJAX is done for a comment system.It takes the value from the form and then with php it inserts it to the databse. The Problem i am haveing is that it just insert empty comment to the database
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>
<script type="text/javascript">
function validateForm()
{
var comment = document.getElementsByName('comment').value;
if (comment == "" )
{
alert("Please fill in all the fields");
return false;
}
else
{
return true;
}
}
</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" onsubmit="return validateForm();">
<label>New Comment</label>
<textarea 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") ?>
My AJAX code.I have tried to do some validation but it doesnt work properly and i dont know what is wrong with it.I am quite new to AJAX so not rlealy able to debug it myself.
$(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()){
alert('You need to write a comment!');
}
else{
$.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);
}
});
}
});
});
My php code to insert into the database.
<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])):
session_start();
include('connection.php');
$connection = connectToMySQL();
$userId = $_SESSION['userID'];
$username = $_SESSION['username'];
$postId = $_POST['postid'];
$comment = $_POST['comment'];
$date_format = " Y-m-d g : i : s";
$time = date ($date_format);
$insertCommentQuery = "INSERT INTO `tblcomments`
(`Content`,`UserID`,`PostID`,`Timestamp`)
VALUES (
'$comment','$userId','$postId',
CURRENT_TIMESTAMP)";
$result = mysqli_query($connection,$insertCommentQuery);
$obj = array();
$obj['id'] = $postId;
$obj['html'] = '<div class="commentcontainer">
<div class="commentusername"><h1> Username :'.$username.'</h1></div>
<div class="commentcontent">'.$comment.'</div>
<div class="commenttimestamp">'.$time.'</div>
</div>';
echo json_encode($obj);
connectToMySQL(0);
endif?>

You never call the function validateForm()
And this part
if (!comment.val()){
alert('You need to write a comment!');
}
will always pass if there is a input field with the class comment, even if it's empty. You could do something like:
//send ajax request
if(validateForm()===false){
alert('You need to write a comment!');
return false;
}
else{
....

You could try to change the comment.val() to comment.text() since you are using a textarea and see if that solves your problem. The change is to be modified in your js code

Related

Deleting a picture with Ajax and php

I have a system where I can upload pictures from different users. Each user can then access a tab where he can see all the pictures that he uploaded by himself. From this tab the user should also be able to click on a button and delete each one induvidually.
I am struggling to make this work so I hope that somebody can help me out.
This is what my database looks like:
table: pictures, rows:
descPicture
id
imageFullNamePicture
titlePicture
userid
table: users, rows:
user_email
user_id
user_name
user_password
user_phone
user_zip
This is my code:
DBH.INC.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chhoe17";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(PDOException $e) {
echo $e->getMessage();
}
UPLOAD.PHP
<?php
include_once 'header.php';
include_once "includes/dbh.inc.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<section class="main-container">
<div class="main-wrapper">
<h2>Manage your pictures</h2>
<?php
//display a message and images if logged in!
if (isset($_SESSION['u_id'])) {
echo "Upload your pictures";
echo '<div class="picture-upload">
<h2>Upload</h2>
<br>
<br>
<br>
<form action="upload.inc.php" id="upload" method="POST" enctype="multipart/form-data">
<input type="text" name="filetitle" placeholder="Image title">
<input type="text" name="filedesc" placeholder="Image description">
<input type="file" id="file" name="file">
<button type="submit" name="submit">Upload</button>
</form>
</div>';
}
if (isset($_SESSION['u_id'])) {
echo ' <section class="picture-links">
<div class="wrapper">
<h2>Pictures</h2> ';
?>
<div id="pictures">
<?php
$sql = "SELECT * FROM pictures WHERE userid = '{$_SESSION['u_id']}'";
//$sql = "SELECT * FROM pictures ORDER BY userid DESC LIMIT 20;";
$stmt = $conn->prepare($sql);
$stmt->execute();
$pictures = $stmt->fetchAll();
// if ($pictures !== null) {
foreach ($pictures as $pic) {
?>
<li>
<figure id="<?php echo $pic['id']; ?>">
<b>
<figcaption><?php echo $pic["titlePicture"] ?>
<img src=<?php echo $pic["imageFullNamePicture"] ?>>
<?php echo $pic["descPicture"] ?> <br>
</figure>
</li>
<span><input type="submit" id="del_btn" value="Delete Image" /></span>
<script type="text/javascript">
$(document).ready(function() {
$("input#del_btn").click(function() {
$.ajax({
type: "POST",
url: "delete.php", //
data: {
id: <?php echo $delid; ?>
},
success: function(msg) {
alert("Your picture has been deleted");
},
error: function() {
alert("failure");
}
});
});
});
</script>
<?php
}
}
?>
</div>
</div>
</section>
</body>
</html>
<?php
include_once 'footer.php';
?>
DELETE.PHP
<?php
include_once "includes/dbh.inc.php";
if (isset($_POST['id'])) {
$picID = $_POST['id'];
$sql = "DELETE FROM pictures WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($picID));
}
?>
As it is right now, nothing happens when I click the delete buttons that are attached to the pictures, and I dont get any alerts either. Any help that somebody could provide to make this work, would be very appreciated.
You're re-using id values, so when your jQuery selector executes which element should it find? Additionally, you're repeating the client-side click handler over and over in your loop. This can all be simplified.
Use a class to identify your "delete" button, and put the relevant id in a data attribute:
<button type="button" class="del_btn" data-id="<?php echo $delid; ?>">Delete Image</button>
Then later, outside the loop, create a single event handler which will listen on all the buttons and use the button's data-id to make the AJAX request:
$('input.del_btn').on('click', function() {
let id = $(this).data('id');
$.post('delete.php', { id: id })
.done(function () {
alert('Your picture has been deleted');
})
.fail(function () {
alert('failure');
});
});

I have a comment form in fullpost.php and the inserting form is in sql.php, how do I get post_id for my comments table?

I have my comment form in fullpost page and I am proccessing a form using ajax, but I don't know how to insert post_id in my comments table to specify the post comment. Kindly help
as I am trying to get the get_id in sql.php but I'm gettng an error which shows undefined post_id in line 13 sql.php
Please find my code below:
fullpost.php
?php
ob_start();
require_once('includes/header.php'); ?>
<?php
$db = new Database();
if(isset($_GET['id'])){
$id = $_GET['id'];
$query = "SELECT * FROM posts WHERE post_id ='$id'";
$post = $db->select($query);
}
$c_query = "SELECT * FROM comments WHERE post_id='$id' ORDER BY comment_id DESC";
$c_run = $db->select($c_query);
?>
<div class ="col-8">
<div class="content-area">
<?php if($post):?>
<?php while($row = $post->fetch_array()):?>
<h2 class="title-full-post"><?php echo $row['title'];?></h2>
<p class="content-area-auth"><?php echo formatDate($row['created_date']);?> By
<a class="content-area-author" href=""><?php echo $row['author']; ?></a></p>
<img class="post-img" src="assets/images/<?php echo $row['image']; ?>">
<p class="content-area-body"><?php echo $row['body'];?><br /><br /><br />
</p>
<?php endwhile; ?>
<?php endif; ?>
<div class="comment">
<h2>Recent Comments</h2>
<?php
if($c_run):
while($r = $c_run->fetch_assoc()):
?>
<p><?php echo $r['name']; echo $r['date']; ?></p>
<p><?php echo $r['comment']; ?></p>
<!--<input type='button' name='reply' id='reply' value='Reply' onclick='replyComment("<?php echo $message_id?>")' />-->
<hr>
<?php
endwhile;
endif;
?>
</div>
<div class="comments-area" id="editbutton">
<h2>Comment Below</h2>
<form action="fullpost" id ="commentForm" method="post" class="form-commment">
<input type="hidden" name="commentId" value="<?php echo $id ?>">
<label for="">Name</label><span style="color: red;">*</span>
<input type="text" name="name" id="commentName" class="form-control-comment" placeholder="Type your Name..">
<label for="">Email</label>
<input type="Email" name="email" id="commentEmail" class="form-control-comment" placeholder="Type your Email..">
<label for="">Website</label>
<input type="text" name="website" id="commentWebsite" class="form-control-comment" placeholder="Type your Website..">
<label for="">Comment</label>
<textarea name="comment" id="commentMessage" class="form-control-comment form-text-area">Comment ...</textarea>
<input type="submit" id="submitComment" name="submitComment" class="btn-comment" value="Post Comment">
<span id="errorMessage"></span>
<span id="successMessage"></span>
</form>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#commentForm").submit(function(event){
event.preventDefault();
var commentName = $("#commentName").val();
var commentEmail = $("#commentEmail").val();
var commentWebsite = $("#commentWebsite").val();
var commentMessage = $("#commentMessage").val();
if(commentName == '' || commentEmail == '' || commentMessage == '' ){
$("#errorMessage").html("Fill all the required fields");
} else{
$("#errorMessage").html('');
$.ajax({
url: "sql.php",
type: "POST",
async: false,
data:{
"done": 1,
"username": commentName,
"useremail": commentEmail,
"userwebsite": commentWebsite,
"usercomment": commentMessage,
"commentId": commentId
},
success: function(data){
//$("#name").val('');
//$("#message").val('');
$("form").trigger("reset");
$("#successMessage").fadeIn().html(data);
}
});
}
});
});
</script>
</div><!--End of Content Area-->
</div><!--end of col-8-->
<?php require_once('includes/footer.php'); ?>
<!--- this is sql.php-->
<?php
require_once('config/config.php');
require_once('libraries/database.php');
require_once('helpers/format_helpers.php');
//require_once('includes/header.php');
//$conn= new mysqli('localhost','root','','myblog');
$db = new Database();
//$id = $_GET['id'];
/*Insert comments*/
if(isset($_POST['done'])){
$name = mysqli_real_escape_string($db->link, $_POST['username']);
$email = mysqli_real_escape_string($db->link, $_POST['useremail']);
$website = mysqli_real_escape_string($db->link, $_POST['userwebsite']);
$comment = mysqli_real_escape_string($db->link, $_POST['usercomment']);
$postId = mysqli_real_escape_string($db->link, $_POST
['commentId']);
if(!empty($name && $email && $comment)){
// $conn= new mysqli('localhost','root','','myblog');
$i_query ="INSERT INTO comments(name, email, website, comment, post_id)VALUES('$name','$email','$website','$comment','$postId')";
$insert_query =$db->insert($i_query);
if($insert_query){
echo "Comment has been submitted and waiting for approval..";
} else{
$error_message ="Please try again..comment not submitted";
}
} else{
$error_message ="All(*)Fields Are required";
}
}
Any assistance would be greatly appreciated
You can use mysql_insert_id() to return the last ID generated my MySQL.
If you show your Database class I can give you an example.

Ajax comment system into a do-while loop

I have a comment system that is working fine. But now I wanna make it work into a loop, so it needs is add an id to identify as unique every "comment box", "submit buttom", so on. Due to there are many classes involved I got lost adding the index to the js function ... and actually everything.
This is my code:
<?php
$sql = mysql_query("SELECT * FROM tblopiniones_persopoli WHERE id_post = '$id_post' AND intActivo = '1' LIMIT 0,10") or die(mysql_error());
while($affcom = mysql_fetch_assoc($sql)){
$name = $affcom['intName'];
$email = $affcom['email'];
$comment = $affcom['strComment'];
$date = $affcom['date'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" />
<div class="thecom">
<h5><?php echo ObtenerNombreFull_Usuario($name); ?></h5><span data-utime="1371248446" class="com-dt"></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt" id="<?php echo $m; ?>">
<span id="">Escribe un comentario ...</span>
</div>
<div class="new-com-cnt">
<a name="coment_box" id="coment_box">
<input type="hidden" id="name-com" name="name-com" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
<input type="hidden" id="mail-com" name="mail-com" value="<?php echo 'xxxxxxx#gmail.com'; ?>" />
<input type="hidden" id="pic-com" name="pic-com" value="<?php echo ObtenerNombreFoto_Usuario($_SESSION['MM_IdUser']); ?>" />
<textarea class="the-new-com" placeholder="Ingresa tu comentario"></textarea>
<div class="bt-add-com">Publicar comentario</div>
<div class="bt-cancel-com">Cancelar</div>
</a>
</div>
My Js code:
<script type="text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#coment_box').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
var thePic = $('#pic-com');
if( !theCom.val()){
alert('¡Por favor escribe un comentario!');
}else{
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val()+'&pic='+thePic.val(),
success: function(html){
theCom.val('');
/*theMail.val('');
theName.val('');*/
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
I'll highly appreciate any help with this lack of knowledge & expertise.
Many thanks in advance.

Ajax comment system, JS doesn't work

I am new and I've been playing around with http://www.webcodo.net/comments-system-using-php-ajax/
I added up some function for pagination, but somehow the JS doesn't work after that
index.php
<?php
$page = (int)(!isset($_GET["page"]) ? 1 : $_GET["page"]);
if ($page <= 0) $page = 1;
$per_page = 3; // Set how many records do you want to display per page.
$startpoint = ($page * $per_page) - $per_page;
$statement = "`comments` ORDER BY `id` DESC";
$results = mysqli_query($db_conn,"SELECT * FROM {$statement} LIMIT {$startpoint} , {$per_page}");
if (mysqli_num_rows($results) != 0) {
// displaying records.
while ($row = mysqli_fetch_array($results)) {
?>
<div class="cmt-cnt">
<div class="thecom">
<h5><?php echo $row['name']; ?></h5><span data-utime="1371248446" class="com-dt"><?php echo $row['date']; ?></span>
<br/>
<p>
<?php echo $row['comment']; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } } ?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input type="text" id="name-com" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail-com" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clear"></div>
<!-- echo $row['name'] . '<br>'; -->
</div><!-- end of comments container "cmt-container" -->
<?php // displaying paginaiton.
echo pagination($statement,$per_page,$page,$url='?');
// var_dump($pagination);
?>
</body>
<!-- JS script -->
<?php include_once('script.js'); ?>
</html>
This is the javascript code :
<script type = "text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#name-com').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
if( !theCom.val()){
alert('You need to write a comment!');
}else{
$.ajax({
type: "POST",
url: "ajax/add-comment.php",
data: 'act=add-com&id_post=+<?php echo $id_post; ?>+&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val(),
success: function(html){
theCom.val('');
theMail.val('');
theName.val('');
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
</script>

Ajax loaded comment not working

My php file loops out each blog post in my database and also creates the comments section. The blogs post great. When I comment on the most recent blog post, the comment does not appear but it seems to add a line as the space expands, just does not include the comment. When I comment on the first post, it works great and exactly as expected. I can't figure out how to correct it. I thought it was a matter of add a .closest to the comment-block selector but that didn't seem to do the trick.
I appreciate any help or feedback!
PHP/HTML
<?php // retrive post
include('php/config.php');
include ('php/function.php');
dbConnect();
$blog_query = mysql_query(
'SELECT *
FROM Blog
ORDER BY DATE DESC');
$date = date_create($row['DATE']);
while($row = mysql_fetch_array($blog_query)): ?>
<div class="post">
<h2><?php echo $row['TITLE']?></h2>
<h3><?php echo date_format($date, 'l, F j, Y')?></h3>
<p><?php echo $row['CONTENT']?></p>
</div>
<h2>Comments.....</h2>
<div class="comment-block">
<?php // retrieve comments with post id
$comment_query = mysql_query(
"SELECT *
FROM Comments
WHERE BID = {$row['ID']}
ORDER BY CID DESC
LIMIT 15") or die(mysql_error());
while($comment = mysql_fetch_array($comment_query)):?>
<div class="comment-item">
<div class="comment-post">
<h3><?php echo $comment['UNAME'] ?> <span>said....</span></h3>
<p><?php echo $comment['COMMENT']?></p>
</div>
</div>
<?php endwhile?>
</div>
<h2>Submit new comment</h2>
<!--comment form -->
<form id="form" method="post">
<div>
<input type="hidden" name="BID" value="<?php echo $row['ID']?>">
<label> <span>Display Name: *</span>
<input id="uname" type="text" tabindex="1" name="commentName" required />
</label>
</div>
<div>
<label> <span>Comment: *</span>
<textarea id="textarea" placeholder="Enter your comment here..." tabindex="2" name="commentMessage" required></textarea>
</label>
</div>
<div>
<input type="submit" id="submit" value="Submit Comment">
</div>
</form>
<?php endwhile?>
</div>
Jquery/Ajax:
var form = $('form');
var submit = $('#submit');
form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'php/ajaxcomment.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(800);
$('.comment-block').append(item);
// reset form and button
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
ajajcomment.php
<?php
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
include('config.php');
include('function.php');
dbConnect();
if (!empty($_POST['commentName']) AND !empty($_POST['commentMessage']) AND !empty($_POST ['BID'])) {
$name = mysql_real_escape_string($_POST['commentName']);
$comment = mysql_real_escape_string($_POST['commentMessage']);
$BID = mysql_real_escape_string($_POST['BID']);
mysql_query("
INSERT INTO Comments
(UNAME, BID, COMMENT)
VALUES('{$name}', '{$BID}', '{$comment}')");
}
?>
<div class="comment-item">
<div class="comment-post">
<h3><?php echo $name ?> <span>said....</span></h3>
<p><?php echo $comment ?></p>
</div>
</div>
<?php
dbConnect(0);
endif?>
What does "php/ajaxcomment.php" return when you post a comment? Pure HTML?
I'd make the "php/ajaxcomment.php" return JSON, for example:
<?php
/*
here you do what ever you do now,
Insert the new comment to database, etc
*/
// Then you return the inserted data:
$data = array(
'UNAME' => $username,
'COMMENT' => $comment,
);
header('Content-Type: application/json');
print json_encode( $data );
?>
..and change the ajax:
...
...
success: function(data){
var commentItem = $('<div/>').addClass('comment-item');
var commentPost = $('<div/>').addClass('comment-post');
var user = $('<h3/>').html( data.UNAME +'<span>said...</span>' );
var comment = $('<p/>').html( data.COMMENT );
commentItem.html( commentPost.html( user + comment ) ).hide().fadeIn(800);
$('.comment-block').append(commentItem);
// reset form and button
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
...
...

Categories

Resources