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
- The document ready function adds and removes the text ‘Leave your
message here…’ from textarea. when you click in the box.
- 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
- 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’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>

