Simple guestbook using ajax

Hello friends, in my previous blog I show you Check uncheck multiple checkboxes using Javascript . Today I Create a simple guestbook using ajax and php. The main logic of the application is that user fill the guestbook form and then user guestbook information validate and save the data in database and user can check the guestbook.

We’ll need a form to prompt the visitor to leave a comment in your guestbook. We’ll need to create some PHP and MySQL code to capture the visitor’s input and save it to the database using ajax. So lets build the simple guestbook using ajax.



First create the database table

DROP TABLE IF EXISTS `guestbook`;
CREATE TABLE IF NOT EXISTS `guestbook` (
  `id` int(4) NOT NULL AUTO_INCREMENT,
  `name` varchar(65) NOT NULL DEFAULT '',
  `email` varchar(65) NOT NULL DEFAULT '',
  `comment` longtext NOT NULL,
  `datetime` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

Create guestbook form(index.php)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Create a simple guestbook using ajax</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
	<link rel="stylesheet" href="style.css" type="text/css" media="screen">
	<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
	<script type="text/javascript" src="js/send_data.js"></script>
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <div class="container">
		<div class="row">
		<div class="span12">
			<div  class="cover">
				<h3>Creating a simple Ajax based PHP guestbook</h3>			
				<div id="result"></div>
				<div id="guestform"> 
					<p class="contact"><label for="name">Name</label></p> 
					<input id="name" name="name" placeholder="Yourname" type="text"> 
					 
					<p class="contact"><label for="email">Email</label></p> 
					<input id="email" name="email" placeholder="admin@admin.com" type="text"> 
			
					<p class="contact"><label for="comment">Your Message</label></p> 
					<textarea name="comment" id="comment" tabindex="4"></textarea> <br>
					
					<input name="submit" id="submit" tabindex="5" value="Save Guestbook" type="submit" style="width:200px;">
				</div> 
				<a href="viewguestbook.php" target="_blank">View Guestbook</a>
			</div>   
		</div>
		</div>
	</div>
  </body>
</html>

Create send_data.js for validate input and send ajax request

$(document).ready(function(){
	$("#submit").click(function() { 
		//get input field values
		var name       		= $('#name').val(); 
		var email      		= $('#email').val();
		var message   	    = $('#comment').val();
		var flag = true;
		/********validate all our form fields***********/
        if(name==""){ 
            $('#name').css('border-color','red'); 
            flag = false;
        }
        if(email==""){ 
            $('#email').css('border-color','red'); 
            flag = false;
        } 
        if(message=="") {  
           $('#comment').css('border-color','red'); 
            flag = false;
        }
		/********Validation end here ****/
		/* If all are ok then we send ajax request to email_send.php *******/
		if(flag) 
        {
			$.ajax({
				type: 'post',
				url: "data_send.php", 
				dataType: 'json',
				data: 'username='+name+'&useremail='+email+'&message='+message,
				beforeSend: function() {
					$('#submit').attr('disabled', true);
					$('#submit').after('<span class="wait">&nbsp;<img src="image/loading.gif" alt="" /></span>');
				},
				complete: function() {
					$('#submit').attr('disabled', false);
					$('.wait').remove();
				},	
				success: function(data)
				{
					if(data.type == 'error')
					{
						output = '<div class="error">'+data.text+'</div>';
					}else{
						output = '<div class="success">'+data.text+'</div>';
						$('input[type=text]').val(''); 
						$('#guestform textarea').val(''); 
					}
					
					$("#result").hide().html(output).slideDown();			
					}
			});
		}
	});

	//reset previously set border colors and hide all message on .keyup()
	$("#guestform input, #guestform textarea").keyup(function() { 
		$("#guestform input, #guestform textarea").css('border-color',''); 
		$("#result").slideUp();
	});
});

Create config.php for database connection

<?php
	$host="localhost"; //Add your SQL Server host here
	$user="root"; //SQL Username
	$pass=""; //SQL Password
	$dbname="test"; //SQL Database Name
	$con=mysqli_connect($host,$user,$pass,$dbname);
?>

Save simple guestbook data in php. Create data_send.php

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{

	//check if its an ajax request, exit if not
	if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
	
		//exit script outputting json data
		$output = json_encode(
		array(
			'type'=>'error', 
			'text' => 'Request must come from Ajax'
		));
		
		die($output);
	} 
	
	//check $_POST vars are set, exit if any missing
	if(!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"]))
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
		die($output);
	}

	//Sanitize input data using PHP filter_var().
	$username       = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
	$useremail      = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
	$message        = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);
	
	//additional php validation
	if(strlen($username)<4) // If length is less than 4 it will throw an HTTP error.
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Name is too short!'));
		die($output);
	}
	if(!filter_var($useremail, FILTER_VALIDATE_EMAIL)) //email validation
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
		die($output);
	}
	if(strlen($message)<5) //check emtpy message
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Too short message!'));
		die($output);
	}
	
	require('config.php');
	
	$sql="INSERT INTO guestbook(name, email, comment, datetime) VALUES('$username','$useremail','$message', now())";
	if (!mysqli_query($con,$sql))
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Could not save data! Please contact administrator.'));
		die($output);
	}
	else
	{
		$output = json_encode(array('type'=>'message', 'text' => 'Values Stored in our Database!. Thank you'));
		die($output);
		echo "Values Stored in our Database!";
	
	}
}
?>		

Now you are done with your guestbook. Now I create a file viewguestbook.php for showing all guestbook result.

<!DOCTYPE html><html lang="en">  
<head>    
	<meta charset="utf-8">    
	<meta http-equiv="X-UA-Compatible" content="IE=edge">   
	<meta name="viewport" content="width=device-width, initial-scale=1">    
	<title>Create a simple guestbook using ajax</title>    
	<!-- Bootstrap -->    
	<link href="css/bootstrap.min.css" rel="stylesheet">   
	<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->    
	<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->   
	<!--[if lt IE 9]>      
	<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>      
	<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>    <![endif]--> 
 </head>  
 <?php require('config.php'); ?>	
 <body>		
	<div class="container">			
		<div class="row">				
			<div class="span12">					
				<table class="table table-bordered">						
					<thead>							
						<tr>								
						<th>Id</th>								
						<th>Name</th>								
						<th>Email</th>								
						<th>Comment</th>								
						<th>Date</th>							
						</tr>						
					</thead>													
					<tbody>						
						<?php						
						$result = mysqli_query($con,"SELECT * FROM guestbook");						
						while($row = mysqli_fetch_array($result))						
						{ ?>							
						<tr>							
						<td><?php echo $row['id']; ?></td>								
						<td><?php echo $row['name']; ?></td>								
						<td><?php echo $row['email']; ?></td>								
						<td><?php echo $row['comment']; ?></td>								
						<td><?php echo $row['datetime']; ?></td>							
						</tr>							
						<?php }							
						mysqli_close($con);						
						?>						
					</tbody>					
				</table>				
			</div>			
		</div>		
	</div>	
 </body>
 </html>

Demo
Download

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •