PHP Ajax Comments

Posted on July 26, 2009 by Ashley

Continuing with a rather ‘Ajax’ theme after the last few tutorials on here i thought I’d go the full way and show you how to create a 140 character php and ajax comments tool. We’re using jQuery to perform the ajax request and create the user experience. You can download all the files needed to get this working at the bottom of this post, it includes the MySQL file to create the database table.

The Code

  1. The document ready function adds and removes the text ‘Leave your message here…’ from textarea. when you click in the box.
  2. Then we have the input .click function. The first section of the code checks that the user has added a comment and if not displays an error prompt telling them to add a message
  3. We then perform the Ajax bit by posting the data to submitComment.php, we show the thank you message and slide in the users comment at the top.

var loaderImage = new Image();
loaderImage.src = 'images/loader.gif';

$(document).ready(function(){
	var messageArea = $('textarea#message');
	messageArea.val('Leave your message here...').css('color', '#666666');
	messageArea.click(function (){
		$(this).val('').css('color', '#000000');
		$(this).unbind('click').click(function(){
			return false;
		});
	});

	$('input#submit-comment').click(function(){
		// Store vars
		var message = messageArea.hide().val();
		// Validation
		if(message.length < 1 || message == "Leave your message here..."){
			messageArea.fadeOut('slow', function(){
				var errorMessage = 'Oops! You haven&#8217;t typed anything. Please have another go...';
				var error = $('<div id="too-short"><span class="error">' + errorMessage + '</span></div>').insertBefore($(this));
				error.hide().fadeIn('slow', function(){
					setTimeout(function(){
						error.hide();
						messageArea.fadeIn('slow');
					}, 2000);
				});
			});
			return false;
		}

		var dataString = 'message='+ message;

		// Show loader
		var loader = $('<div id="loader"><img class="load-gif" src="' + loaderImage.src + '" /></div>').insertBefore($(this));

		//alert (dataString);
		$.ajax({
			type: "POST",
			url: "submitComment.php",
			data: dataString,
			success: function(data) {
				$('div#loader').find('img.load-gif').remove();
				$('div#loader').append('<span class="success">Thanks for your comment!</span>');
				$('div#loader').hide().fadeIn('slow');
				$('span.limit').remove();
				$('div#comments').prepend(data);
				$('div#comments div.comment-unapproved:nth-child(1)').hide().slideDown('slow');
				$('input#submit-comment').unbind('click').click(function(){
					return false;
				});
			}
		});
		return false;
	});
	messageArea.keyup(function(){
		var limit = 140;
		var currentLength = $(this).val().length;
		var charsLeft = limit - currentLength;
		$('span.limit').html(charsLeft);
		if(currentLength >= limit){
			$(this).val($(this).val().substring(0, limit));
			$('span.limit').html('0');
			var textarea = document.getElementById('message');
			textarea.scrollTop = textarea.scrollHeight + 9999;
		}
	});
});

The index.php main code


include("dbConnector.php");
$connector = new DbConnector();

function date_diff($d1, $d2){
	$d1 = (is_string($d1) ? strtotime($d1) : $d1);
	$d2 = (is_string($d2) ? strtotime($d2) : $d2);

	$diff_secs = abs($d1 - $d2);
	$base_year = min(date("Y", $d1), date("Y", $d2));

	$diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
	$diffArray = array(
		"years" => date("Y", $diff) - $base_year,
		"months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
		"months" => date("n", $diff) - 1,
		"days_total" => floor($diff_secs / (3600 * 24)),
		"days" => date("j", $diff) - 1,
		"hours_total" => floor($diff_secs / 3600),
		"hours" => date("G", $diff),
		"minutes_total" => floor($diff_secs / 60),
		"minutes" => (int) date("i", $diff),
		"seconds_total" => $diff_secs,
		"seconds" => (int) date("s", $diff)
	);
	if($diffArray['days'] > 0){
		if($diffArray['days'] == 1){
			$days = '1 day';
		}else{
			$days = $diffArray['days'] . ' days';
		}
		return $days . ' and ' . $diffArray['hours'] . ' hours ago';
	}else if($diffArray['hours'] > 0){
		if($diffArray['hours'] == 1){
			$hours = '1 hour';
		}else{
			$hours = $diffArray['hours'] . ' hours';
		}
		return $hours . ' and ' . $diffArray['minutes'] . ' minutes ago';
	}else if($diffArray['minutes'] > 0){
		if($diffArray['minutes'] == 1){
			$minutes = '1 minute';
		}else{
			$minutes = $diffArray['minutes'] . ' minutes';
		}
		return $minutes . ' and ' . $diffArray['seconds'] . ' seconds ago';
	}else{
		return 'Less than a minute ago';
	}
}

// Work out the Date plus 8 hours
// get the current timestamp into an array
$timestamp = time();
$date_time_array = getdate($timestamp);

$hours = $date_time_array['hours'];
$minutes = $date_time_array['minutes'];
$seconds = $date_time_array['seconds'];
$month = $date_time_array['mon'];
$day = $date_time_array['mday'];
$year = $date_time_array['year'];

// use mktime to recreate the unix timestamp
// adding 19 hours to $hours
$timestamp = mktime($hours + 8,$minutes,$seconds,$month,$day,$year);
$theDate = strftime('%Y-%m-%d %H:%M:%S',$timestamp);

$query = "SELECT * FROM shoutbox ORDER BY ID DESC LIMIT 30";
$result = $connector->query($query);
while($row = $connector->fetchArray($result)) {
	$date = strtotime($row['date']);
	$dayMonth = date('d M', $date);
	$year = date('y', $date);
	$message = $row['content'];
	$datediff = date_diff($theDate, $date);
?>
		<div class="comment">
			<div class="date">
				<span class="day-month"><?php echo $dayMonth; ?></span>
				<span class="year"><?php echo $year; ?></span>
			</div>
			<span class="content"><?php echo stripslashes($message);?> <span class="time"><?php echo $datediff; ?></span></span>
			<div class="clear"></div>
		</div>
<?php
}
?>
	</div>
	<div id="submission">
		<form name="comment-submission">
			<textarea id="message" name="message"></textarea>
			<span class="limit">140</span>
			<input type="submit" id="submit-comment" value=" " />
		</form>
		<div class="clear"></div>
	</div>

demodownload

This entry was posted in Downloads, Javascript, PHP, Tutorials, jQuery, popular and tagged , , , . Bookmark the permalink.
Comments
64 discussions around PHP Ajax Comments
Older Comments
  1. Hello Ashley.

    Give me a heads up when you’ve updated the code. :)

  2. I’ve figured it out, thanks.

  3. Wale Afolabi says:

    Thanks, for the script really waht i’ve been looking for. Am sort of new to Php and Ajax and i have a little question. I intend using this comment script across multiple pages which should have their different comments. Could you please suggest an effecient way of doing this? Thanks

  4. hups says:

    hello nice but i have this error on localhost with xampp

    Fatal error: Cannot redeclare date_diff() in D:\xampp\htdocs\shoutbox(3)\shoutbox\index.php on line 139

    can you help please

  5. Ashley says:

    @hups what have you done to modify the code? the download works straight out of the folder.

  6. hups says:

    i have nothing make only db and config to db

  7. firas says:

    i think there is something wrong with the download file

  8. Bigaltheking says:

    Hey Ashely,
    Script looks awesome, i was wondering if there is a way to limit the amount of comments on a page, and once there are more, it would add pages of comments.

    eg. http://www.cbc.ca – there comments on any stories.

    So if the comments counted 10, then the 11th would be at page 2 of the comments.

    Im a pure amatuer at this kinda stuff, i do understand the basics, any help would be awesome.

    Thanks,

  9. kp says:

    can you send me these files would love to play with this. It seems the download link is broke.

  10. Elvin says:

    I am having problems with this as well. Getting error on page 139 in index.php like others.

  11. Joseph says:

    Awesome! Just the ticket I’ve been looking for. Have a video blog, and want people to be able to comment without interrupting the playback of the video. Thanks for the post!

  12. Anwar says:

    Great Post Ashley. Thanks a bunch. It works for me.

    I was trying to add another field where the user also enters their Name with the comments. I added a new row to the table called “name”, but i am having issues inserting this. Can you help me with this?

    Added this to the files (index and submit)

    $ query is:
    $message = $row['content'];
    $visitor = $row['name'];

    Span is:

    Get the message:
    $theVisitor = addslashes(strip_tags($_POST['visitor']));
    $theMessage = addslashes(strip_tags($_POST['message']));

    $theQuery = “INSERT INTO shoutbox (content, date, name) VALUES (‘” . $theMessage . “‘, ‘” . $theDate . “‘, ‘” . $theVisitor . “‘)”;

    As you can see, i am still learning. But any correction would be greatly appreciated
    When i insert names into the DB with a query, they do get displayed on the index page, but i am unable to insert them thru the website form

  13. Has says:

    well done

Older Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribers
1,250
Twitter
510
Comments
1,207
Posts
125