Overview to writing an AJAX style comment box

Write a html file with a form asking the user for input(doesn't have to be a form).

The submit button calls a JavaScript function.

The JavaScript function asks the server to run a php file (or someother server side script).

As the server deals with this request, the server will change the 'readystate'.
Each time the 'readystate' is changed, the JavaScript function 'onreadystatechange' is called.

Once the server responds, the Javascript updates some part of your html file.

comment.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.
org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
	<!--Include the javascript file, this file has the 'submitForm' function that will get called when 
	the user clicks the submit button  -->
	<script type="text/javascript" src="comment.js"></script>
</head>


<body>
	<!-- Create the 'form' make sure you set onSubmit as below, the javascript function will deal with 
	submiting the form-->
	<form name="MWD_form" onSubmit="return(false)">
	<div class="form_content">
		<!--Create a label and input for user name -->
		<label>Name</label><br />
		<input type="text" name="MWD_form_name" /><br />
		<!--Create label and textarea for the user message -->
		<label>Message</label> <br />
		<textarea id="MWD_textarea" cols="20" rows="5" type="text" name="MWD_form_comment" ></textarea><br 
		/>
	</div>
	<div class="form_human_check">
		<!--Create label, imput and an image for the human check  -->
		<label>Please enter the text seen below</label> <br />
		<input type="text" name="MWD_form_human_check" /><br />
		<img id="human_check_image" src="http://www.myleswebdesign.co.uk/images/humancheck/image1.jpg" /><
		br /> 
	</div>
	<div class="clear"></div>
		<!--Add a Submit button with an onClick event handler called submitForm() this function can be 
		found 
		in the comment.js file that was included near the start of this file.
		The function takes 2 parameters, the first is this which is a pointer to this Document , called 
		'this'
		, the second is the name of the MySql table -->
		<input name="Submit" type="button" value="Submit" onClick="submitForm(this,'Tb_CommentsBox_ajax')" 
		/><br />
	</form>

	<!-- AJAX style javascript will now update the contents of this element when the server has 
	processed the user input -->
	<div id="show_comments">
	<!--The first time the page is loaded, we want to print the contents of the table,
	so we set the varible MWD_table to the name of the MySql table that we want to print ,
	and then call print.php	-->
	<?php 
	$MWD_table ="Tb_CommentsBox_ajax";
	include("print.php"); 
	?>
	</div>
	
</body>

</html>

comment.js

function submitForm(MWD_form,tablename){
var url = "comment.php";
//The last part of the params varible is the table name. As a security measure I begin all my MySql 
table names with 
//a secret code. In all my HTML and JavaScript files I refer to my tables with the secret code left 
off the start.
//Here I add the secret code back, it is the "Your_prefix" part  
//This is just a precaution to stop people knowing the names of my tables.
var params = "MWD_form_name=" + document.MWD_form.MWD_form_name.value + 
"&MWD_form_comment=" + document.MWD_form.MWD_form_comment.value  + 
"&MWD_form_human_check=" + document.MWD_form.MWD_form_human_check.value +
"&tablename=" +"Your_Prefix" +tablename;

var xmlhttp;  

// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
	{
 	 	xmlhttp=new XMLHttpRequest();
  	}
// code for IE6, IE5
else
	{
  		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  	}
 
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("connection", "close");
xmlhttp.send(params);


xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4 && xmlhttp.status==200)
		{//This changes the content of my element with ID = show_comment to the response text
		//that the server sent.
			document.getElementById('show_comments').innerHTML=xmlhttp.responseText;
		}
		if((xmlhttp.readyState == 2)||(xmlhttp.readyState == 3))
		{//This changes the content of my element with ID = show_comment to 'Sending request'
		//You probably will never see this because my code is very simple. The server sends the response
		//and your computer updates the element before you will notice this.
			document.getElementById('show_comments').innerHTML = 'Sending request';
		}
	}
}

comment.php

<?php
//Thses four variables name must be the same as those used to set up your MySql server
$MWD_sqlserver = "localhost";
$MWD_sqldatabase = "Your_Data_base";
$MWD_sqluserid = "Your_User_Id";
$MWD_sqlpassword = "Your_Password";

//If you want to alter MWD_form_name or MWD_form_comment or MWD_form_human_check or tablename
// remember to change the variable names in the form as well.
$MWD_name = $_POST['MWD_form_name'];
$MWD_comment = $_POST['MWD_form_comment'];
$MWD_human_check = $_POST['MWD_form_human_check'];
$tablename = $_POST['tablename'];

$MWD_timestamp = date(DATE_W3C);


//Connect to the MySql server, this is frequently call 'localhost' but it is just a name, 
//and therfore can be called anything
if(!($MWD_Con = mysqli_connect($MWD_sqlserver, $MWD_sqluserid, $MWD_sqlpassword) or die(mysqli_error(
   $MWD_Con))))
{ printf("Errormessage: %s\n", mysqli_error($MWD_Con));
}
//the next four lines make sure the user input won't be dangerous to the MySql server
$MWD_name = mysqli_real_escape_string($MWD_Con,$MWD_name);
$MWD_comment = mysqli_real_escape_string($MWD_Con,$MWD_comment);
$MWD_human_check = mysqli_real_escape_string($MWD_Con,$MWD_human_check);
$tablename = mysqli_real_escape_string($MWD_Con,$tablename);
//Select the database, you must set this up yourself. I did it by logging on at www.mywebsite.
com/cpanel
if(!(mysqli_select_db($MWD_Con,$MWD_sqldatabase) or die(mysqli_error($MWD_Con))))
{ printf("Errormessage: %s\n", mysqli_error($MWD_Con));
}
// Create a MySQL table in the selected database, (if it already exists do nothing)
if(!(mysqli_query($MWD_Con,"CREATE TABLE IF NOT EXISTS $tablename(
id INT NOT NULL AUTO_INCREMENT, 
PRIMARY KEY(id),
 MWD_col_name VARCHAR(40), 
 MWD_col_comment VARCHAR(1000),
 MWD_col_timestamp VARCHAR(60))")or die(mysql_error())))
{ printf("Errormessage: %s\n", mysqli_error($MWD_Con));
}

//did the user enter the code that was shown to them in the picture?
if($MWD_human_check == "YOUR_CODE" || $MWD_human_check == "your_code")
{
	$MWD_human_check=TRUE;
}
else
{   //If they didn't pass the test, then set the variable to false,
	$MWD_human_check=FALSE;
	//Display a message to the screen so the user knows what happened.
	echo "<br />"; 
  echo "<div class='system_message'>";
	echo "<div class='label_author'>";
		echo "Author:";
	echo"</div>";
	echo "<div class='author'>";
		echo "SYSTEM MESSAGE";
	echo "</div>";
	echo "<br /> " ;
	echo "<div class='comment'>";
		echo "YOU HAVE FAILED TO ENTER THE TEXT DISPLAYED IN THE IMAGE CORRECTLY. PLEASE TRY AGAIN";
	echo "</div>";
  echo "</div>";//end of message class div tag
  echo "<br />";
}

//if the user inputed something for the name and comment and they passed the human check 
// then run this code
if($MWD_name && $MWD_comment && $MWD_human_check)
{
	//Insert the name and comment from the user in the table
	if(!(mysqli_query($MWD_Con,"INSERT INTO $tablename (MWD_col_name, MWD_col_comment, 
    MWD_col_timestamp) VALUES('$MWD_name','$MWD_comment','$MWD_timestamp') ")))
	{ printf("Errormessage 137 : %s\n", mysqli_error($MWD_Con));}
}
else//Both fields are empty so do nothing, you could maybe give an error message
{}

//Get the entire contents of the table. Use this line to reverse the order '"ORDER BY  `id` DESC"
if(!($result = mysqli_query($MWD_Con,"SELECT * FROM $tablename ORDER BY  `id` DESC")))
	{ printf("Errormessage 140: %s\n", mysqli_error($MWD_Con));}
//for every row of the table, print the author and comments colums
while($row = mysqli_fetch_array($result))
  {
  echo "<br />"; 
  echo "<div class='message'>";
	echo "<div class='label_author'>";
		echo "Author:";
	echo"</div>";
	echo "<div class='author'>";
		echo $row['MWD_col_name'];
	echo "</div>";
	echo "<div class='timestamp'>";
		echo $row['MWD_col_timestamp']; 
	echo "</div>";
	echo "<br /> " ;
	echo "<br /> " ;
	echo "<div class='comment'>";
		echo $row['MWD_col_comment'];
	echo "</div>";
  echo "</div>";//end of message class div tag
  echo "<br />";
  }
mysqli_free_result($result);
mysqli_close($MWD_Con); 
?>

print.php

<?php
//This file is used to print any of my tables (which are in a specific format)
//I set a variable to the name of the table in my database that I want to print 
//(minus the first few characters)
//here I add the first few characters back on to the start of the variable
//This is just a precaution to stop people knowing the names of my tables

//THIS VARIABLE MUST BE SET BEFORE INCLUDING THIS FILE
$MWD_table='Your_prefix'.$MWD_table;

$MWD_sqlserver = "localhost";
$MWD_sqldatabase = "Your_Data_base";
$MWD_sqluserid = "Your_User_Id";
$MWD_sqlpassword = "Your_Password";

//connect to the MySQl server
if(!($MWD_Con = mysqli_connect($MWD_sqlserver, $MWD_sqluserid, $MWD_sqlpassword) or die(mysqli_error(
   $MWD_Con))))
{ printf("Errormessage: %s\n", mysqli_error($MWD_Con));
}
//select the choosen database in the previously seltected server
if(!(mysqli_select_db($MWD_Con,$MWD_sqldatabase) or die(mysqli_error($MWD_Con))))
{ printf("Errormessage: %s\n", mysqli_error($MWD_Con));
}
//Get the entire contents of the table. Use this line to reverse the order '"ORDER BY  `id` DESC"
if($result = mysqli_query($MWD_Con,"SELECT * FROM $MWD_table ORDER BY  `id` DESC"))
{
	//for every row of the table, print the author and comments colums
	while($row = mysqli_fetch_array($result))
  	{
		echo "<br />"; 
		echo "<div class='message'>";
		echo "<div class='label_author'>";
			echo "Author:";
		echo"</div>";
		echo "<div class='author'>";
			echo $row['MWD_col_name'];
		echo "</div>";
		echo "<div class='timestamp'>";
			echo $row['MWD_col_timestamp']; 
		echo "</div>";
		echo "<br />" ;
		echo "<br />" ;
		echo "<div class='comment'>";
			echo $row['MWD_col_comment'];
		echo "</div>";
		echo "</div>";//end of message class div tag
		echo "<br />";
  	}
}
else//if there was a error returned when we tried to get the entire contents of the table
{ 
	printf("Errormessage 140: %s\n", mysqli_error($MWD_Con));
	printf("No table yet defined in the database");
}
//all done so free the memory used for the results and close the connection
mysqli_free_result($result);
mysqli_close($MWD_Con); 
?>













  MylesWebDesign.co.uk   ©2010