Adding image to comment box - javascript

Thanks for your time guys.
I have the following code working for my commenting system though I can't really be sure about the security for now. But I need your help guys in :
Allowing anyone that comment to add their image to their comment whether registered users or Visitors
Building the inside comment or reply box. This is what I got.
Comment for comment counter
Here is the PHP code for the comment:
<?php
// Connect to the database
include('config.php');
$id_post = "1"; //the post or the page id
?>
<div class="cmt-container" >
<?php
$sql = mysql_query("SELECT * FROM comments WHERE id_post = '$id_post'") or die(mysql_error());;
while($affcom = mysql_fetch_assoc($sql)){
$name = $affcom['name'];
$email = $affcom['email'];
$comment = $affcom['comment'];
$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 $file_path; ?>" height="250" />
<div class="thecom">
<h5><?php echo $name; ?></h5><span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $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>
</div><!-- end of comments container "cmt-container" -->
<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>
And the Ajax Script :
<?php
extract($_POST);
if($_POST['act'] == 'add-com'):
$name = htmlentities($name);
$email = htmlentities($email);
$comment = htmlentities($comment);
// Connect to the database
include('../config.php');
// 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;
if(strlen($name) <= '1'){ $name = 'Guest';}
//insert the comment in the database
mysql_query("INSERT INTO comments (name, email, comment, id_post)VALUES( '$name', '$email', '$comment', '$id_post')");
if(!mysql_errno()){
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" alt="" />
<div class="thecom">
<h5><?php echo $name; ?></h5><span class="com-dt"><?php echo date('d-m-Y H:i'); ?></span>
<br/>
<p><?php echo $comment; ?></p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<?php endif; ?>

Related

How to Create Load More With PHP and PDO

i want to create load more to my site, but when i try to click load more it just load 2 items.
my index.php
<div class="postList">
<?php
// Include the database configuration file
include 'koneksi.php';
// Get records from the database
$query = $db->prepare("SELECT * FROM master_post, posting WHERE master_post.master_post_name = posting.master_post_name AND posting.sticky = 'Normal' ORDER BY posting.idpost DESC LIMIT 2");
$query->execute();
if($query->rowCount() > 0){
while($row = $query->fetch()){
$postID = $row['idpost'];
?>
<div class="list_item"><?php echo $row['file_name']; ?></div>
<?php } ?>
<div class="show_more_main" id="show_more_main<?php echo $postID; ?>">
<span id="<?php echo $postID; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading...</span></span>
</div>
<?php } ?>
</div>
my javascript
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.postList').append(html);
}
});
});
});
</script>
my ajax_more.php
if(!empty($_POST["id"])){
// Include the database configuration file
include 'koneksi.php';
// Count all records except already displayed
$query = $db->prepare("SELECT COUNT(*) as num_rows FROM master_post, posting WHERE master_post.master_post_name = posting.master_post_name AND posting.sticky = 'Normal' AND posting.idpost < ".$_POST['id']." ORDER BY posting.idpost DESC");
$row = $query->fetch();
$totalRowCount = $row['num_rows'];
$showLimit = 2;
// Get records from the database
$query = $db->query("SELECT * FROM master_post, posting WHERE master_post.master_post_name = posting.master_post_name AND posting.sticky = 'Normal' AND posting.idpost < ".$_POST['id']." ORDER BY posting.idpost DESC LIMIT $showLimit");
if($query->rowCount() > 0){
while($row = $query->fetch()){
$postID = $row['idpost'];
?>
<div class="list_item"><?php echo $row['file_name']; ?></div>
<?php } ?>
<?php if($totalRowCount > $showLimit){ ?>
<div class="show_more_main" id="show_more_main<?php echo $postID; ?>">
<span id="<?php echo $postID; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading...</span></span>
</div>
<?php } ?>
<?php
}
}
I'm not sure where the mistake is. im using tutorial from this site https://www.codexworld.com/load-more-data-using-jquery-ajax-php-from-database/

AJAX comment system, ajax not working

I am making a comment system for my blog that I am creating and currently I have two problems with it. The form appears under every post. But only works on the top post. The rest of the forms simply don't work.
The another problem I have is that I'm using ajax and the form does add the record to SQL but I still have to refresh my page for it to show. I want it to show automatically straight away after it is added.
tl:dr
Two problems:
The only form that works is the first one under the first post, the rest simply don't work
Ajax doesn't automatically show the comments, need to refresh to seem them
Code:
JQuery
function post()
{
var comment = document.getElementById("comment").value;
var name = document.getElementById("name").value;
var mail = document.getElementById("mail").value;
var post_id = document.getElementById("post_id").value;
if(comment && name && mail)
{
$.ajax
({
type: 'post',
url: 'php/comment.php',
data:
{
user_comm:comment,
user_name:name,
user_mail:mail,
post_id:post_id,
},
success: function (response)
{
document.getElementById("comments").innerHTML=response+document.getElementById("comments").innerHTML;
document.getElementById("comment").value="";
document.getElementById("name").value="";
document.getElementById("mail").value="";
}
});
}
return false;
}
Index.php
<div class="container">
<div class="row">
<div class="col-lg-8">
<?php
$result = mysql_query('SELECT * FROM `posts` ORDER BY id DESC') or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$id_post = $row['id'];
$post_title = $row['post_title'];
$post_date = $row['date_created'];
$post_img = $row['post_img'];
$post_first = $row['post_first'];
$post_second = $row['post_second'];
echo " <!-- Blog Post Content Column -->
<h1> " . $row['post_title'] . " </h1><p class='lead'>
by <a href='#'>Matt</a></p> <hr>
<p><span class='glyphicon glyphicon-time'>" . $row['date_created'] . "</span></p>
<img class='img-responsive' style='width: 900px;height: 300px;' src=" . $row['post_img'] . "> <hr>
<p class='lead'>" . $row['post_first'] . "</p>
<p>" . $row['post_second'] . "</p> <hr>";
?>
<!-- Comments Form -->
<div class='well'>
<h4>Leave a Comment:</h4>
<div class="new-com-cnt">
<form method='post' onsubmit="return post();">
<input type='hidden' id='post_id'name='post_id' value='<?php echo $id_post; ?>'>
<div class='form-group'>
<input type="text" id="name" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea type='text' id='comment' name='comment' class="form-control" rows='3'></textarea>
</div>
<input type="submit" value="Post Comment">
</form>
</div>
</div>
<hr>
<?php
$resultcomments = mysql_query("SELECT * FROM `comment` WHERE post_id = '$id_post' ORDER BY `date` DESC") or die(mysql_error());
while($affcom = mysql_fetch_assoc($resultcomments)){
$name = $affcom['name'];
$email = $affcom['mail'];
$comment = $affcom['comment'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<!-- Posted Comments -->
<div id='comments'class='media'>
<a class='pull-left' href='#'>
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'><?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
}
?>
</div>
comment.php
include_once('../../acp/db/db.php');
$link = mysql_connect($dbhost, $dbuser, $dbpassword, $dbname);
mysql_select_db($dbname);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if(isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['user_mail']))
{
$comment=$_POST['user_comm'];
$name=$_POST['user_name'];
$mail=$_POST['user_mail'];
$post_id=$_POST['post_id'];
$insert=mysql_query("INSERT INTO comment (name,mail,comment,post_id) VALUES ('$name', '$mail', '$comment', '$post_id')");
$select=mysql_query("SELECT * FROM `comment` WHERE post_id = '$id_post' ORDER BY `date` DESC");
if($row=mysql_fetch_array($select))
{
$name=$row['name'];
$comment=$row['comment'];
$date=$row['date'];
?>
<div class='media'>
<a class='pull-left' href='#'>
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'><?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
exit;
}
?>
This is the first time I am playing around with AJAX :) so be easy on me Any help will be appreciated.
I tested all your code. It's working now. I commented it overall, so search after "NB" (lat. for "Nota bene") in codes, in order to see were I made relevant changes. I'll describe here some problems with it and I'll also give you some recommendations - if I may. At last I'll insert the three corrected pages.
Problems:
One big problem was, that you were using the $id_post variable in
the SELECT sql statement (in comment.php), which does not exist
in comment.php code.
Other problem: DOM elements had same ids. The DOM elements inside
loop-forms must have unique id attributes. You must always have
unique id attributes in html elements. Give them the form
id="<early-id><post_id>" for example.
There were also other problems in more places. I commented overall,
so you'll have to read my codes.
Recommendations:
Use mysqli_ instead of mysql_ functions, because mysql
extension were completely removed from PHP >= 7.0.
Use exception handling, especially when dealing with db access.
Don't write HTML code from inside php. Alternate php with html if you
wish, but don't do echo "<div class=...></div>" for example. This
is actually very important if you use an IDE which can format your
html code. If this code is inside php, you have no chance for this
beautifying process. therefore you can miss important html-tags
without knowing it, because your IDE didn't showed you where tags are
really missing in page.
In html tags: use same name as id. Example: id=mail<?php echo
$post_id; ?>, name=mail<?php echo $post_id; ?>. Exception: radio
buttons, checkboxes and all tags which can form a group. Then, each
tag would have a unique id, but all of them would receive the same
name.
Use '' overall and "" inside them. Maintain this "standard", you'll see it's a lot better than the inverse.
Corrected pages:
Index.php:
<?php
try {
$con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
if (!$con) {
throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NB: TITLE</title>
<!-- NB: Added my scripts for testing -->
<link href="Vendor/Bootstrap-sass-3.3.7/Bootstrap.css" rel="stylesheet" type="text/css" />
<script src="Vendor/jquery-3.1.0/jquery.min.js" type="text/javascript"></script>
<script src="Vendor/Bootstrap-sass-3.3.7/assets/javascripts/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-8">
<?php
$result = mysqli_query($con, 'SELECT * FROM `posts` ORDER BY id DESC');
if (!$result) {
throw new Exception('The query could not be executed!');
}
while ($row = mysqli_fetch_array($result)) {
// NB: Unified $post_id name overall (instead of $id_post).
$post_id = $row['id'];
$post_title = $row['post_title'];
$post_date = $row['date_created'];
$post_img = $row['post_img'];
$post_first = $row['post_first'];
$post_second = $row['post_second'];
?>
<!-- Blog Post Content Column -->
<!--
NB: Extracted html code from php and added here, where it should be.
-->
<h1>
<?php echo $post_title; ?>
</h1>
<p class="lead">
by Matt
</p>
<hr/>
<p>
<span class="glyphicon glyphicon-time">
<?php echo $post_date; ?>
</span>
</p>
<img class="img-responsive" style="width: 1200px; height: 100px;" src="<?php echo $post_img; ?>">
<hr/>
<p class="lead">
<?php echo $post_first; ?>
</p>
<p>
<?php echo $post_second; ?>
</p>
<hr/>
<!-- Comments Form -->
<div class="well">
<h4>Leave a Comment:</h4>
<div class="new-com-cnt">
<form method="post" onsubmit="return post('<?php echo $post_id; ?>');">
<!--
NB: Deleted hidden input (not needed!) and was missing post_id in "id" attribute!
So: transfered post_id value to post() function as argument. See js too.
-->
<!--
NB: Added post_id to the "id" attributes. See js too.
-->
<div class="form-group">
<input type="text" id="name<?php echo $post_id; ?>" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail<?php echo $post_id; ?>" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea type="text" id="comment<?php echo $post_id; ?>" name="comment" class="form-control" rows="3"></textarea>
</div>
<input type="submit" value="Post Comment">
</form>
</div>
</div>
<hr>
<!--
NB: Added new "comments" outer-container in order to append
new comment to it and added post_id value into its "id" attribute.
See the js too.
-->
<div id="comments<?php echo $post_id; ?>" class="comments-container">
<?php
$resultComments = mysqli_query($con, 'SELECT * FROM `comment` WHERE post_id = ' . $post_id . ' ORDER BY `date` DESC');
if (!$resultComments) {
throw new Exception('The query could not be executed!');
}
while ($affcom = mysqli_fetch_assoc($resultComments)) {
$name = $affcom['name'];
$email = $affcom['mail'];
$comment = $affcom['comment'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
?>
<!-- Posted Comments -->
<!--
NB: deleted id attribute "comments", because I added an outer
container to hold the insert results, e.g. the div
with the class "comments-container".
-->
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="<?php echo $grav_url; ?>" >
</a>
<div class="media-body">
<?php echo $name; ?>
<h4 class="media-heading">
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
?>
</div>
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
<?php
$closed = mysqli_close($con);
if (!$closed) {
throw new Exception('The database connection can not be closed!');
}
} catch (Exception $exception) {
// NB: Here you should just DISPLAY the error message.
echo $exception->getMessage();
// NB: And here you should LOG your whole $exception object.
// NB: Never show the whole object to the user!
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
?>
comment.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NB: TITLE</title>
</head>
<body>
<?php
try {
$con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
if (!$con) {
throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
}
if (isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['user_mail'])) {
$comment = $_POST['user_comm'];
$name = $_POST['user_name'];
$mail = $_POST['user_mail'];
$post_id = $_POST['post_id'];
// NB: NEW. CHANGE THIS TO YOUR wished DATE FORMAT.
// Use UNIX timestamps for dates, so that you make good date calculations.
$date = date("Y-m-d");
// NB: INSERT DATE IN DB TOO, so that you can select by date desc down under.
$insert = mysqli_query($con, "INSERT INTO comment (name,mail,comment,post_id, date) VALUES ('$name', '$mail', '$comment', '$post_id', '$date')");
if (!$insert) {
throw new Exception('The query could not be executed!');
}
// NB: Replaced $id_post with $post_id.
$select = mysqli_query($con, "SELECT * FROM `comment` WHERE post_id = '$post_id' ORDER BY `date` DESC");
if (!$select) {
throw new Exception('The query could not be executed!');
}
if ($row = mysqli_fetch_array($select)) {
$name = $row['name'];
// NB: Added email, because it wasn't provided.
$email = $row['mail'];
$comment = $row['comment'];
$date = $row['date'];
// NB: It wasn't provided, so I added the same value as in index.php.
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
?>
<div class="media">
<a class='pull-left' href='#'>
<!--
NB: Where is your $grav_url value?! I added one of mine for testing.
-->
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'>
<?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
// NB: Don't use exit(). Let the code flow further, because
// you maybe want to close the db connection!
// exit();
}
$closed = mysqli_close($con);
if (!$closed) {
throw new Exception('The database connection can not be closed!');
}
} catch (Exception $exception) {
// NB: Here you should just DISPLAY the error message.
echo $exception->getMessage();
// NB: And here you should LOG your whole $exception object.
// NB: Never show the whole object to the user!
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
?>
</body>
</html>
Javascript file:
// NB: Added post_id as parameter. See form too.
function post(post_id) {
// NB: Added post_id value to the "id" attributes. See form too.
var comment = document.getElementById("comment" + post_id).value;
var name = document.getElementById("name" + post_id).value;
var mail = document.getElementById("mail" + post_id).value;
if (comment && name && mail) {
$.ajax({
type: 'post',
url: 'php/comment.php',
data: {
user_comm: comment,
user_name: name,
user_mail: mail,
post_id: post_id
},
success: function (response) {
// NB: Comments-post_id is now an outer container. See form.
// NB: Added post_id value to the "id" attributes. See form too.
document.getElementById("comments" + post_id).innerHTML = response + document.getElementById("comments" + post_id).innerHTML;
document.getElementById("comment" + post_id).value = "";
document.getElementById("name" + post_id).value = "";
document.getElementById("mail" + post_id).value = "";
}
});
}
return false;
}
// ******************************************************************************
// NB: Recommendation:
// ******************************************************************************
// Use jquery and ajax instead of vanilla javascript. It's no problem anymore ;-)
// Use done, fail, always instead of success, error, ....
// ******************************************************************************
//function post(post_id) {
// var comment = $('#comment' + post_id);
// var name = $('#name' + post_id);
// var mail = $('#mail' + post_id);
//
// if (comment && name && mail) {
// var ajax = $.ajax({
// method: 'POST',
// dataType: 'html',
// url: 'php/comment.php',
// data: {
// user_comm: comment.val(),
// user_name: name.val(),
// user_mail: mail.val(),
// post_id: post_id
// }
// });
// ajax.done(function (data, textStatus, jqXHR) {
// var comments = $("#comments" + post_id);
//
// // NB: I'm not sure, not tested, too tired :-) Please recherche.
// comments.html(data + comments.html());
//
// comment.val('');
// name.val('');
// mail.val('');
// });
// ajax.fail(function (jqXHR, textStatus, errorThrown) {
// // Show error in a customized messages div, for example.
// $('#flashMessage').val(textStatus + '<br />' + errorThrown);
// });
// ajax.always(function (data, textStatus, jqXHR) {
// //...
// });
// }
//
// return false;
//}
// ******************************************************************************
Good luck.
Your parent loop is generating several comments form and they all have the same id. Ids are supposed to be unique for the whole document. refer this. Perhaps this is causing other comment forms not to work except the first one.
Your second problem is not an issue. It is general behavior of how server works. When you are using ajax, it is sending data to the server which stores it in the database. Server's job is done. It cannot send the data back to the page and update the page content without refreshing the page. You can initiate another ajax call after posting to server in order to refresh the content of the page.
And though it is not related to the question. Try to be consistent with your use of single quotes and double quotes. You shouldn't randomly choose them. Decide on one and use them consistently. And yes do try to learn PDO or mysqli. I will suggest PDO.

how to restrict the user not to post again on the same page if already posted

I have the below code for User Rating & Comment system which is working fine, but user can post and rate again and again.
I want that if a user posted comment already he/she should not see the comment box but a message that " You have already posted comment on this page".
I tried by using the query in the Add-Comment.php but did not worked.
Need help to solve this issue. Thanks
URL: index.php?id=1
Add-Comment.php
<?php
session_start();
$ipaddress = $_SERVER["REMOTE_ADDR"];
$users = session_id();
if(!empty($_POST)){
extract($_POST);
if($_POST['act'] == 'add-com'):
$comment = htmlentities($comment);
$rating = htmlentities($rating);
// Connect to the database
require_once '../../inc/db.php';
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . "?d=" . $default . "&s=" . $size;
$sql = "INSERT INTO rest_rating (rate, comment, sr_id, ip, user)
VALUES ('$rating', '$comment', '$id_post', '$ipaddress', '$users')";
$sqls = "select user from rest_rating
where sr_id = '$id_post' and user ='$users' )";
$tt = $db->query($sqls);
if ( $tt['user'] == $users ) {
echo '<font size="3" color="red">You Have Already Rated For This Restaurant</font>';
}elseif ( $db->query($sql)==true) {
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" alt="" />
<div class="thecom">
<!--<h5><?php echo $name; ?></h5>-->
<b>Rating : </b><?php echo $rating; ?>
<span class="com-dt"><?php echo date('d-m-Y H:i'); ?></span>
<br/>
<p><?php echo $comment; ?></p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<?php endif; ?>
<?php } ?>
index.php
<?php
require_once '../../inc/db.php';
$id=$_GET['id'];
?>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<link type="text/css" rel="stylesheet" href="css/example.css">
<link href="css/star-rating.css" media="all" rel="stylesheet" type="text/css"/>
<script src="js/star-rating.js" type="text/javascript"></script>
<div class="container">
<h3>Comments</h3>
<?php
$id_post = $id;
?>
<div class="cmt-container" >
<?php
session_start();
$users = session_id();
$results = $db->query("SELECT * FROM rest_rating WHERE sr_id = $id_post");
foreach ($results as $affcom) {
$comment = $affcom['comment'];
$rating = $affcom['rate'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . "?d=" . $default . "&s=" . $size;
?>
<div class="cmt-cnt">
<div class="thecom">
<input id="input-5a" class="rating" value="<?php echo $rating; ?>" data-size="xs" data-show-clear="false" data-show-caption="false" data-readonly="true">
<span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $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 name="starrating" id="starrating" value="1" type="number" class="rating" min=0 max=5 step=1 data-size="xs2" >
<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>
</div><!-- end of comments container "cmt-container" -->
<?php
$sqls = "select user from rest_rating
where sr_id = '$id_post' and user ='$users' )";
$tt=$db->query($sqls);
$userT=$tt['user'];
?>
<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 starrating = $('#starrating');
if( !theCom.val()){
alert('You need to write a comment!');
}else{
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&rating='+starrating.val()+'&comment='+theCom.val(),
success: function(html){
theCom.val('');
starrating.val('');
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
</script>
</div>
You can construct a query to check whether the user has already posted a comment on that particular page or not, and display the rating and comment box accordingly. Here's the code snippet,
// your code
$results = $db->query("SELECT * FROM rest_rating WHERE sr_id = '". $id_post . "' AND user ='". $users . "'");
if($results->num_rows){
// user has already posted a comment
echo '<p>You have already posted comment on this page</p>';
}else{
// user hasn't posted any comment on this page yet
// display rating and comment box
?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input name="starrating" id="starrating" value="1" type="number" class="rating" min=0 max=5 step=1 data-size="xs2" >
<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>
</div><!-- end of comments container "cmt-container" -->
<?php
}
// your code

Dynamically values parse to Popup Model Box from PHP Page

I was trying to parse the php data values which inside the while loop to the popup model .
Sample Code
<?php
include("connect.php");
$sql = 'SELECT id FROM products WHERE tag="mixed" ORDER BY id DESC LIMIT 5';
mysql_select_db('levels');
$retval = mysql_query( $sql, $db_server );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$id = $row['id'];
?>
<div onclick="showDialog('#dialog6');show_data();">
<div id="getid">
<?php echo $id; ?>
</div>
</div>
<?php
}
mysql_close($db_server);
?>
<script>
function showDialog(id){
var dialog = $(id).data('dialog');
dialog.open();
}
function show_data(){
var x = document.getElementById("getid").innerHTML;
document.getElementById("demo").innerHTML = x;
}
</script>
<!-- Popup Model -->
<div data-role="dialog" id="dialog6" >
<div id="demo"> </div>
</div>
Let's say if i have id => 1 to 10 , above code writing last 5 items from the table. which are 6 7 8 9 10 . ( it's working perfectly ) .
my requirement is to when i click the 7 it should parse 7 to the popup model. ( or let's say to the innerHTML of ).
it only parsing the first value ( 5 ) . to all onclick events when i click the each number.
PS : this is test using mysql not mysqli or pdo :) .
Thanks in Advance !
Try this. Hope it helps.
$sql = 'SELECT id FROM products WHERE tag="mixed" ORDER BY id DESC LIMIT 5';
mysql_select_db('levels');
$retval = mysql_query( $sql, $db_server );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$id = $row['id'];
?>
<div onclick="showDialog('#dialog6');show_data(<?php echo $id; ?>);"> <!-- Changed -->
<div id="getid<?php echo $id; ?>"> <!-- Changed -->
<?php echo $id; ?>
</div>
</div>
<?php
}
mysql_close($db_server);
?>
<script>
function showDialog(id){
var dialog = $(id).data('dialog');
dialog.open();
}
function show_data(y){ // Changed
var x = document.getElementById("getid"+y).innerHTML; // Changed
document.getElementById("demo").innerHTML = x;
}
</script>
<!-- Popup Model -->
<div data-role="dialog" id="dialog6" >
<div id="demo"> </div>
</div>
Try This One.
<?php
include("connect.php");
$sql = 'SELECT id FROM products WHERE tag="mixed" ORDER BY id DESC LIMIT 5';
mysql_select_db('levels');
$retval = mysql_query( $sql, $db_server );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$id = $row['id'];
?>
<div onclick="showDialog('#dialog6');show_data(<?php echo $id; ?>,'<?php echo $name; ?>','<?php echo $imgUrl; ?>');"> <!-- Changed -->
<div id="id<?php echo $id; ?>"> <!-- Changed -->
<?php echo $id; ?>
</div>
<div id="name<?php echo $name; ?>"> <!-- Changed -->
<?php echo $id; ?>
</div>
<div id="image<?php echo $id; ?>"> <!-- Changed -->
<img src="<?php echo $imgUrl; ?>" />
</div>
</div>
<?php
}
mysql_close($db_server);
?>
<script>
function showDialog(id){
var dialog = $(id).data('dialog');
dialog.open();
}
function show_data(id, name, imgUrl){ // Changed
document.getElementById("dispID").innerHTML = id;
document.getElementById("dispName").innerHTML = name;
document.getElementById("ImgDisplay").src = imgUrl;
}
</script>
<!-- Popup Model -->
<div data-role="dialog" id="dialog6" >
<div id="demo"> <!-- Changed -->
<div id="dispID"></div>
<div id="dispName"></div>
<div id="dispImg"><img id="ImgDisplay" src="" /></div>
</div>
</div>

AJAX comment system Validation problems

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

Categories