I have created a simple add and delete comments system using php. Couple issues with it.
So I am assuming my best option is go go with ajax route to do this without refreshing the page. Say below is the basic setup to add and show comment. How would you create the ajax for it?
Add comment form
<form action="" method="post" enctype="multipart/form-data">
<div class="field-comment">
<label for="name">Enter your comment</label><br>
<input type="text" name="comment" size="60">
</div>
<input type="submit" value="Post">
</form>
Show comments
<div id="show-comments"></div>
Delete comment button
<div class="delete_comment">
<a href="delete_comment.php?id=<?php echo $comment_id; ?>"><p><img src="images/icon_del.gif" alt="delete"></p></a>
</div>
So these are the delete functions I have in the head section of the website.
<script>
function deleteClick () {
deleteComment($(this).data('id'));
}
function deleteComment(id) {
$.ajax('delete_comment.php', {
type: 'POST',
data: {
id: id
},
success: function() {
//Ajax successful: remove the comment div from your comment area
$('.comment-' + id).remove();
},
error: function() {
//Ajax not successful: show an error
alert('An error occured while deleting the comment!');
}
});
}
$('.delete_comment').click(deleteClick);
</script>
This is the delete div on say index.php
<div id="comment-<?php echo $comment_id; ?>" class="comment">
This is a comment.
<a data-id="<?php echo $comment_id; ?>" href="#" class="delete_comment">
<p><img src="images/icon_del.gif" alt="delete"></p>
</a>
</div>
This is the delete function from delete_comment.php
$delete = $dbh->prepare("DELETE from comments WHERE comment-id = {$comment_id}");
You can use this to display a live feed of your comments:
setInterval(function showcomments() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
csxmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
csxmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
csxmlhttp.onreadystatechange=function comments()
{
if (csxmlhttp.readyState==4 && csxmlhttp.status==200)
{
document.getElementById('show-comments').innerHTML=csxmlhttp.responseText;
}
}
csxmlhttp.open('GET','show_comments.php',true);
csxmlhttp.send();
}, 1000);
And this to send the id of the comment to the php script that will delete the comment from the database and then alert()
you when it has been deleted:
function deletecomment() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
dcxmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
dcxmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
dcxmlhttp.onreadystatechange=function dcomment()
{
if (dcxmlhttp.readyState==4 && dcxmlhttp.status==200)
{
alert('Comment Deleted!')
}
}
dcxmlhttp.open('GET','delete_comment.php?id=' + comment_id,true);
dcxmlhttp.send();
}
Is this what you were looking for??
You can make your thispage.php
more like:
<?php
/* execute comments query -- echo $comments with the proper HTML formatting
surrounding each comment */
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<style type='text/css'>
@import 'common.css'; @import 'thispage.css';
</style>
</head>
<body class='njs'>
<div class='field-comment'>
<label for='comment'>Enter your comment</label>
<input type='text' name='comment' id='comment' maxsize='60' />
<input type='button' name='pst' id='pst' value='Post' />
</div>
<div id='added-comments'>
<div id='comments'><?php echo $comments;?></div>
</div>
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='post.js'></script>
<script type='text/javascript' src='thispage.js'></script>
</body>
</html>
Now let's see common.js
:
//<![CDATA[
var doc = document, bod = doc.body, IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
bod.className = 'js';
function gteIE(version, className){
if(IE >= version)bod.className = className;
}
function E(e){
return doc.getElementById(e);
}
//]]>
Now your learning. Here's post.js
:
//<![CDATA[
function post(where, send, success){
var x = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
var v = encodeURI(send);
x.open('POST', where); x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.setRequestHeader('Content-length', v.length); x.setRequestHeader('Connection', 'close');
x.onreadystatechange = function(){
if(x.readyState === 4 && x.status === 200){
success(x.responseText);
}
}
x.send(v);
}
//]]>
Now we need to see thispage.js
:
//<![CDATA[
E('pst').onclick = function(){
var cmt = E('comment').value;
if(cmt !== ''){
post('response.php', 'comment='+cmt, function(o){
var div = doc.createElement('div'), del = doc.createElement('input');
del.type = 'input'; del.value = 'Delete';
div.appendChild(doc.createTextNode(o)); div.appendChild(del);
E('comments').appendChild(div);
});
}
else{
// a comment was not entered
}
}
var psts = E('comments').childNodes, cn, ip;
for(var i=0,l=psts.length; i<l; i++){
(function(i){
cn = psts[i].childnodes;
for(var n=0,c=cn.length; n<c; n++){
(function(n){
ip = cn[n];
if(ip.nodeName.match(/^input$/i)){
ip.onclick = function(){
post('response.php', 'delete='+ip.previousSibling.nodeValue, function(o){
if(o){
bod.removeChild(ip.parentNode);
}
else{
// put error code here
}
});
}
}
})(n);
}
})(i);
}
//]]>
How about response.php
:
<?php
if(isset($_POST['comment'])){
$cmnt = $_POST['comment'];
/* run database table column row INSERT based on $cmnt -- echo $cmnt when query
is executed correctly
*/
}
elseif(isset($_POST['delete'])){
/* run database table column row DELETE based on the actual comment which you
can find in $_POST['delete'] -- Once you have executed query echo 1, which
will go back to JavaScript page `onreadystatechange`
*/
}
?>
First you need to alter your form a little bit:
<form action="#">
<div class="field-comment">
<label for="commentText">Enter your comment</label><br>
<input type="text" name="commentText" id="commentText" size="60">
</div>
<input type="submit" value="Post">
</form>
Then, using jQuery, the script would be something like:
//Event handler for click on a delete button
function deleteClick () {
deleteComment($(this).data('id'));
}
function addComment(commment) {
//Create a new div with id "comment-[id]" containing the comment
var $commentDiv = $('<div />', {
id: 'comment-' + comment.id,
'class': 'comment',
html: comment.text
};
//Create the delete button with the attribute data-id,
//which will be used for deleting
var $deleteLink = $('<a href="#" data-id="' + comment.id + '"/>', {
'class': 'delete_comment',
html: '<p><img src="images/icon_del.gif" alt="delete"></p>',
click: deleteClick //Reference to the event handler we created above
});
//Add the delete button to the comment div
$commentDiv.append($deleteLink);
//Add the comment div to your comment area
$('#show-comments').append($commentDiv);
}
function deleteComment(id) {
$.ajax('delete_comment.php', {
type: 'POST',
data: {
id: id
},
success: function() {
//Ajax successful: remove the comment div from your comment area
$('#comment-' + id).remove();
},
error: function() {
//Ajax not successful: show an error
alert('An error occured while deleting the comment!');
}
});
}
$(function() {
$('#comment-form').submit(function(event) {
//Skip the form from submitting
event.preventDefault();
var commentText = $(this).find('#commentText').val();
//Ensure commentText to not be empty
if($.trim(commentText).length) {
$.ajax('add_comment.php', {
type: 'POST',
data: {
commentText: commentText
},
success: function(response) {
//Ajax successful: call the addComment function
addComment(response);
},
error: function() {
//Ajax not successful: show an error
alert('An error occured while saving the comment!');
}
};
}
});
//Find all delete buttons and add the event handler we created above.
//This expects the delete buttons to have a data-id attribute containing
//the id of the comment that should be deleted
$('.delete_comment').click(deleteClick);
});
This does the following:
$(function() {})
) and add an event handler to the form for the submit eventevent.preventDefault()
)if($.trim(commentText).length)
) and call the ajax functionid
and text
. id
is the id of the newly added comment and text
just contains the added textdeleteComment
function on clickThis should do the job, but I haven't tested it. See the jQuery documentation for more details about the ajax functionality. jQuery may seem a bit of an overhead for just this functionality, but it makes stuff like sending ajax and creating new DOM elements a lot easier. Please tell me if I need to clarify something.
Edit
As requested in the comments this is an example for a div containing a comment and a delete button:
<div id="comment-1234" class="comment">
This is a comment.
<a data-id="1234" href="#" class="delete_comment">
<p><img src="images/icon_del.gif" alt="delete"></p>
</a>
</div>
A click on the delete button takes the value of the attribute data-id
($(this).data('id')
in the code) and calls the function deleteComment
with the id as the attribute (1234 in this case). The function sends an ajax request and deletes the div with the id "comment-[id]", so in this example "comment-1234".