Ajax Contact Form

Below is a simple way to use Ajax for a website contact form. I’ve created the full thing using one script (which can be added to any page using the php include function).

I’ll come back to this page in the near future to explain more about how the script hangs together - but if you have experience with PHP and JavaScript it will look pretty straightforward.

If you decide to use this - please note I have not fully tested this for bugs or security flaws, so use at your own risk.

Hopefully you can extend this to fit your own needs.

So here it is - just save it as ajax_contact.php and use: include ‘ajax_contact.php’; in you php file to have it work. (remember to update the email address!)

<?
if(!isset($rnd) || !isset($name) || !isset($email) || !isset($subject) || !isset($body)) {
	showform();
} else {
	processform();
}

function processform(){
	global $name, $email, $subject, $body;

	$email_to1 = "foo@hotmail.com"; // enter your email here
	$email_from1 = $mail;
	$email_to2 = $mail;
	$email_from2 = $email_to1;
	$email_subject = "Contact Form: ".stripslashes($subject);
	$email_message = "Please find below a message submitted by '".stripslashes($name);
	$email_message .="' on ".date("d/m/Y")." at ".date("H:i")."nn";
	$email_message .="--------- START OF SUBMITTED MESSAGE ---------nn";
	$email_message .= stripslashes($body);
	$email_message .="nn--------- END OF SUBMITTED MESSAGE ---------nn";

	$confirmation_subject = "Thank you for your message";
	$confirmation = "This is to confirm we have received your message....";

	// SEND EMAIL TO email_to2 - confirmation
	$headers = 'From: '.$email_from2."rn" .
   'Reply-To: '.$email_from2."rn" .
   'X-Mailer: PHP/' . phpversion();

	mail($email_to2, $email_subject, $confirmation, $headers);

	// SEND EMAIL TO email_to1 - message to you!!
	$headers = 'From: '.$email_from1."rn" .
   'Reply-To: '.$email_from1."rn" .
   'X-Mailer: PHP/' . phpversion();

	mail($email_to1, $email_subject, $email_message, $headers);

	echo "Thank You.";
	die();
} // end processform()

function showform() {
?>
<STYLE type="text/css">
div.row {
  clear:both;
  }
div.row span.label {
  float: left;
  width: 60px;
  text-align: right;
  }
div.row span.formw {
  float: right;
  width: 220px;
  text-align: left;
  }
div.row span.left {
  float: left;
  text-align: left;
  font-weight: bold;
  color: #fff;
  width: 49%;
  }
div.row span.right {
  float: right;
  text-align: right;
  font-weight: bold;
  color: #fff;
  width: 49%;
  }
div.row span.submit{
  width:280px;
  text-align:center;
}
#form{
	width: 300px;
	background-color: #f6f6f6;
	border: 1px dotted #666;
	padding: 2px;
	margin: 0px auto;
}
#confirmation{
	width: 300px;
	height:220px;
	background-color: #f6f6f6;
	border: 1px dotted #666;
	padding: 2px;
	margin: 0px auto;
	text-align: center;
  font-weight: bold;
}
</STYLE>
<script type="text/javascript">
<!--
var http = createRequestObject();
var areal = Math.random() + "";
var real = areal.substring(2,6);

function createRequestObject() {
	var xmlhttp;
	try { xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); }
  catch(e) {
    try { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
    catch(f) { xmlhttp=null; }
  }
  if(!xmlhttp&&typeof XMLHttpRequest!="undefined") {
  	xmlhttp=new XMLHttpRequest();
  }
	return  xmlhttp;
}

function sendRequest() {
	var rnd = Math.random();
	var name = escape(document.getElementById("name").value);
	var email = escape(document.getElementById("email").value);
	var subject = escape(document.getElementById("subject").value);
	var body = escape(document.getElementById("body").value);

	try{
    http.open('POST',  'ajax_contact.php');
    http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    http.onreadystatechange = handleResponse;
		http.send('name='+name+'&email='+email+'&subject='+subject+'&body='+body+'&rnd='+rnd);
	}
	catch(e){}
	finally{}
}

function check_values() {
	var valid = document.getElementById("valid").value;
	if(real !== valid) {
		alert("Ant-Bot check failed.....nPlease enter the 4 digits as they appear.");
		return false;
	}

	var name = document.getElementById("name").value;
	var email = document.getElementById("email").value;
	var subject = document.getElementById("subject").value;
	var body = document.getElementById("body").value;
	if(trim(name) == "" ||
		trim(email) == "" ||
		trim(subject) == "" ||
		trim(body) == "") {
			alert("Please complete all fields");
	} else {
		if(isEmail(email)) {
			document.getElementById("submit").disabled=true;
			document.getElementById("submit").value='Please Wait..';
			sendRequest();
		} else {
			alert("Email appears to be invalid.nPlease check.");
			document.getElementById("email").focus();
			document.getElementById("email").select();
		}
	}
}

function handleResponse() {
	try{
    if((http.readyState == 4)&&(http.status == 200)){
    	var response = http.responseText;
      document.getElementById("confirmation").innerHTML = response;
      document.getElementById("confirmation").style.display ="";
      document.getElementById("form").style.display = "none";
		}
  }
	catch(e){}
	finally{}
}

function isUndefined(a) {
   return typeof a == 'undefined';
}

function trim(a) {
	return a.replace(/^s*(S*(s+S+)*)s*$/, "$1");
}

function isEmail(a) {
   return (a.indexOf(".") > 0) && (a.indexOf("@") > 0);
}

function botCheckInfo() {
	alert("To prevent automatic programs (bots)nfrom submitting spam through this form,nwe have added a simple validationncheck to the form. You must enter nthese 4 digits in the box provided innorder to submit the form.");
}
 // -->
 </script>

<?
} // end showform()
?>

<div id="form">
<form>
<div class="row"><span class="label">Name:</span>
	<span class="formw"><input type="text" id="name" size="30" /></span></div>
<div class="row"><span class="label">Email:</span>
	<span class="formw"><input type="text" id="email" size="30" /></span></div>
<div class="row"><span class="label">Subject:</span>
	<span class="formw"><input type="text" id="subject" size="30" /></span></div>
<div class="row"><span class="label">Message:</span>
	<span class="formw"><textarea cols="23" rows="6" id="body"></textarea></span></div>
<div class="row" align="center"><a href="javascript:botCheckInfo()">Anti-bot check</a>. Enter Digits '<b><script language="javascript">document.write(real)</script></b>' below:</div>
<div class="row" align="center"><input type="text" id="valid" size="15" /></div>
<div class="row" align="center">&nbsp;</div>
<div class="row" align="center">
	<input type="button" value="Submit" id="submit" onClick="return check_values();"></div>
</form>
</div>

<div id="confirmation" style="display:none"></span>

Here is a screenshot of the form:

Ajax Contact Form

Again - I will come back to this page and explain a bit more about how this script works.