PHP and MySql Comment Form without Refreshing Page with jQuery

Advertisement

In this tutorial I’ll show you how to create an advance comment form in PHP and MySQL with jQuery without refreshing page in just a few lines of codes all we need to do is initialize the submitted post data and pass using jQuery API, display response and done, the data submitted is constructed using PHP, so sounds simple right? Yes it is.

Past few years Google introduces web 2.0 in their Gmail project with jQuery and now web programming is going crazy, adding and optimizing web using jQuery to save time, smooth and with elegant look.

Demo

To view demo page click here

index.html

Here our HTML codes that contains the basic input data name, email, url and message.


<!--Error and success message wrapper-->
<div id="errAll"></div>

<!--Lists of comments posts wrapper-->
<div class="commentpost"></div>

<!--Comment form-->
<form method="post" id="formcomment">
   <label for="name">Name</label>
   <p><input type="text" name="name" id="name" value="<?php echo (isset($_POST['name']) ? $_POST['name'] : ''); ?/>" /></p>

   <label for="email">Email</label>
   <p><input type="text" name="email" id="email" value="<?php echo (isset($_POST['email']) ? $_POST['email'] : ''); ?/>" /></p>
   <label for="website">URL</label>
   <p><input type="text" name="url" id="url" value="<?php echo (isset($_POST['url']) ? $_POST['url'] : ''); ?/>" /></p>

   <label for="website">Message</label>
   <p><textarea cols="40" rows="6" name="message" id="message"><?php echo (isset($_POST['message']) ? $_POST['message'] : ''); ?></textarea></p>

   <p><input type="submit" name="submitter" value="Submit Comment" /></p>
   <p><input type="hidden" name="task" value="addComments" /></p>
</form>

Javascript Code

$("#formcomment").submit() – formcomment is the ID of the FORM tag. If user submit the form, the data posted to ajax.php without refreshing the page(thanks to jQuery for the JS library) and result or response data is appended to commentpost class.

In here we’re using $.post() jquery API, it Load data from the server using a HTTP POST request, for more information about this API visit jQuery api site.


<script type="text/javascript">
jQuery(document).ready(function($){
	$("#formcomment").submit(function(){
		ctask = this.task.value;
		cname = this.name.value;
		cemail = this.email.value;
		curl = this.url.value;
		cmessage = this.message.value;
		submitter = this.submitter;

		// you can use PHP for double validation
		if( cname=="" || cemail=="" || cmessage=="" )
			$("#errAll").html('<p>Invalid Captcha. Please try again.</p>');

		var data = {
			task: ctask,
			name: cname,
			email: cemail,
			url: curl,
			message: cmessage
		};
		$.post("ajax.php", data, function( response ) {
			if( '0' == response ) {
				$("#errAll").html('<p>Please don\'t leave the requierd fields.</p>');
			} else if( '1' == response ) {
				$("#errAll").html('<p>Invalid Email Address, Please try again.</p>');
			} else {
				submitter.value="Comment posted";
				submitter.disabled=true;
				$(response).appendTo($(".commentpost"));
			}
		});

		return false;

	});
});
</script>

ajax.php

This contains PHP codes that construct the submitted data and MySQL code to insert data to tbl_comment table.


<?php
// include config.php file, this contains our DB connection
include_once( 'config.php' );

if( isset($_POST['task']) && 'addComments' == $_POST['task'] )
{
	$name = addslashes(trim($_POST['name']));
	$email = addslashes(trim($_POST['email']));
	$url = addslashes(trim($_POST['url']));
	$comment = htmlentities(addslashes(trim($_POST['message'])));
	$date = date('F j, Y');

	if ($name == "" || $email == "" || $url == "" || $comment == "") {
		echo '0';
	} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
		echo '1';
	} else {
		$sql=mysql_query("INSERT INTO tbl_comment(name, email, url, message, date_posted) VALUES ('$name', '$email', '$url', '$comment', '$date')");
		if($sql) {
		echo '
			<div class="commentbox">
				<div class="commentboxt">'.$name.' </div>
					<div class="commentboxm">
						<p class="wrap">
							'. $comment .'
						</p>
					</div>
				<div class="commentboxb">'. $date .'</div>

		';
		}
	}

}
?>

Database

You can do this easily using PHPMyAdmin, or you can use the code below and execute commands in MySQL Console.


CREATE TABLE IF NOT EXISTS 'tbl_comment' (
  'id' INT(11) NOT NULL AUTO_INCREMENT,
  'name' VARCHAR(225) NOT NULL,
  'email' VARCHAR(225) NOT NULL,
  'url' VARCHAR(225) NOT NULL,
  'message' TEXT NOT NULL,
  'date_posted' VARCHAR(225) NOT NULL,
  PRIMARY KEY ('id'),
  UNIQUE KEY 'email' ('email')
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

config.php

This contains PHP database configuration file.


<?php
$host='HOSTNAME';
$user='USERNAME';
$pass='PASSWORD';
$db='DATABASE';

$con = mysql_connect($host, $user, $pass) or die(mysql_error() . 'Oops! there is a problem connecting to database');
mysql_select_db($db, $con) or die('Error selecting database '. mysql_error());
?>

That’s it, hope your find this tutorial helpful, for your feedback you can add comment below.

Advertisement