Geekpedia Programming Tutorials






How to create an AJAX contact form

This tutorial shows users how to create an AJAX contact form. The form method in this tutorial is set to POST.

On Wednesday, May 3rd 2006 at 03:30 PM
By Nabeel Akhtar (View Profile)
****-   (Rated 3.4 with 5 votes)
Contextual Ads
More PHP Resources
Advertisement
Before we begin the tutorial, view the AJAX Contact Form in action.


The AJAX Contact Form uses the POST method to transfer the data from the form to the PHP file. From thereon you can store the data in variables using "$_POST". This is also illustrated in the code.

There are two pages that you will need. The first page will show the form to the user when the user first visits the page. We will call this page "Form.php". The other page will process the data from the first page and will return a confirmation message. You can use PHP or any other language to do anything you want. We are going to call the second page "Process.php".

To get started, first create a form:

Ajax Form

There are two <span> sections defined in this page. The first one is highlighted in orange in the above image and the second span is the table that holds the input fields.

The status span will display the status of the form while it is being processed. Once all the information has been processed, the status will read "Ready".

Following is the code for the Form.php file:

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>AJAX Contact Form NabeelAkhtar.NET</title>
<link rel="stylesheet" type="text/css" href="../../../style.css">

<!------------------------------------------------ AJAX CODE ---------------------------------->
<script type="text/javascript" language="javascript">
var http_request = false;

function show_hint ( p_hint_text, p_span ) {
document.getElementById(p_span).innerHTML = p_hint_text ;
}

function makePOSTRequest(url, parameters, SpanName) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}

http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById(SpanName).innerHTML = result;
document.getElementById('status').innerHTML = 'Ready';
} else {
alert('There was a problem with the request.');
}
}
};
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}


function Contact(obj,SpanName) {
var curDateTime = new Date(); //For IE
var poststr = "name=" + encodeURI( document.getElementById("name").value ) +
"&email=" + encodeURI( document.getElementById("email").value ) +
"&uniqueID=" + curDateTime +
"&msg=" + encodeURI( document.getElementById("msg").value ) ;
var SpanName = SpanName;
//alert (SpanName);
makePOSTRequest('Process.php', poststr, SpanName);
}


</script>
<!------------------------------------------------ END AJAX CODE ---------------------------------->

</head>

<body>
<table width="316" border="0" cellpadding="4" cellspacing="0" class="blueBorder">
<tr>
<td colspan="2" class="title1"><a href="http://www.nabeelakhtar.net">Tutorials @ NabeelAkhtar.NET</a><a href="http://www.nabeelakhtar.net"></a> </td>
</tr>
<tr>
<td width="141" class="title1">AJAX Contact Form </td>
<td width="157" class="orange">Status: <span class="greenBold" id="status">Ready</span> </td>
</tr>
</table>

<span id="ContactFormSpan">
<table width="316" border="0" cellpadding="4" cellspacing="0" class="blueBorder">
<form action="javascript:Contact(document.getElementById('ContactForm'),'ContactFormSpan'); show_hint('Sending Data, Please Wait...', 'status');" method="post" name="ContactForm" id="ContactForm">

<tr>
<td width="141" align="right" class="normal">Name:</td>
<td width="157"><input name="name2" type="text" class="inputBlack" id="name" size="20" maxlength="50" /></td>
</tr>
<tr>
<td align="right" class="normal">Email:</td>
<td><input name="email2" type="text" class="inputBlack" id="email" size="20" maxlength="50" /></td>
</tr>
<tr>
<td align="right" class="normal">Message:</td>
<td><input name="msg2" type="text" class="inputBlack" id="msg" size="20" maxlength="50" /></td>
</tr>
<tr>
<td align="right" class="normal">&nbsp;</td>
<td><input name="Submit2" type="submit" class="buttonBlue" value="Submit" /></td>
</tr>
<tr>
<td colspan="2" align="left" class="normal">Note: This is a demo form. This form will NOT send out emails. </td>
</tr>

</form>
</table>
</span>
</body>
</html> 


Following is the code for the "Process.php" file:

<?php

$name = stripslashes($_POST['name']);
$email = stripslashes($_POST['email']);
$msg = stripslashes($_POST['msg']);

echo "
<table width=\"316\" border=\"0\" cellpadding=\"4\" cellspacing=\"0\" class=\"blueBorder\">
<tr>
<td align=\"left\" class=\"title1\">Your Information has been processed</td>
</tr>
<tr>
<td align=\"left\" class=\"normal\">Name: $name <br> Email: $email <br> Message: $msg</td>
</tr>
<tr>
<td align=\"left\" class=\"normal\">Note: This is a demo form. This form will NOT send out emails. </td>
</tr>
<tr>
<td align=\"left\" class=\"normal\"><a href=Form.php>Try Again</a></td>
</table>";

?>



More Tutorials at NabeelAkhtar.NET

Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by necenzurat on Tuesday, May 16th 2006 at 10:33 AM

veary nice, do u know that with ajax u can save veary much of your bandwitch

by Nabeel Akhtar on Tuesday, May 16th 2006 at 10:55 AM

Well it depends what you are doing with AJAX... For example the auto-refresh pages end up using more bandwidth... If pages are refreshed at even a higher rate, the page will just eat up your bandwidth.

by cdcdscscdc on Saturday, July 1st 2006 at 07:38 AM

by Johan on Saturday, August 19th 2006 at 05:47 AM

It is indeed a very nice example, but there is one thing that should also be mentoined.

When you insert text that is none english like the french é, ç, à, è then you get weird results if you save your form output in to a database (when you don't save that as utf-8). Displaying it in on a page (with echo) doesn't reveal this but if you look at your decoded url data (http header) then you'll see that the text was encoded in utf-8. This is absolutely normal because the xmlhttprequest object always sends this encoded data as utf-8.

So when you save characters like é, ç, à you get the following results in your database (column collation is in latin1):

é => é

This is not expected because when you want to search for a field that contains this character you will get no results because the database doesn't see this character as é.

Displaying it on a webpage with you header set to iso-8859-1 is no problem, but your data is saved wrongfully.

To avoid this you should always save data in utf-8, but the bigest problem is that php internally doesn't support utf-8 and then you loose the ability to perform string functions on the requested data. There are librarys and functions out there to perform these string functions on utf8 data but they require extra process time (greater script execution time) and extra coding.

I wanted to write this because it's important to see all the aspects of using ajax with php.

by Johan on Saturday, August 19th 2006 at 08:44 AM

I also posted a topic on this on the phparch website.

You can view the topic by following this url: http://www.phparch.com/discuss/index.php?t=msg&th=4203

by ajaxlines on Saturday, January 27th 2007 at 06:27 PM

At <a href="http://www.ajaxlines.com">Ajaxlines</a> you can find a full list of Ajax tutorials, services and presentations.

by ajaxlines on Saturday, January 27th 2007 at 06:28 PM

At Ajaxlines you can find a full list of Ajax tutorials, services and presentations.

I think you have to visit it now ... http://www.ajaxlines.com

by O_o on Monday, February 12th 2007 at 11:48 PM

No security

by Vivian on Thursday, December 13th 2007 at 10:56 AM

rtrter

by Bober on Friday, February 8th 2008 at 04:42 AM

<a href="http://www.digitalcamerainfo.com/bbs/member.php?u=1860">buy viagra online</a><br><a href="http://www.dealdatabase.com/forum/member.php?u=68538">Buy levitra</a><br><a href="http://www.gamecareerguide.com/forums/member.php?u=2520">buy cialis online</a><br><a href="http://extjs.com/forum/member.php?u=24461">buy cialis</a><br><a href="http://extjs.com/forum/member.php?u=24461?generic+cialis">generic cialis</a><br><a href="http://www.gamecareerguide.com/forums/member.php?u=2478">cheap cialis</a><br><a href="http://forum.springframework.org/member.php?u=34111">generic viagra</a><br><a href="http://www.layersmagazine.com/forum/member.php?u=4276">buy viagra</a><br><a href="http://forum.springframework.org/member.php?u=34111?cheap+viagra">cheap viagra</a><br><a href="http://ringtones.forum5.com">download free ringtones</a><br><a href="http://forum.springframework.org/member.php?u=34397">buy valium</a><br><a href="http://forum.springframework.org/member.php?u=34397?buy+valium+online">buy valium online</a><br><a href="http://forums.ipodhacks.com/member.php?u=35372">buy tramadol</a><br><a href="http://forums.ipodhacks.com/member.php?u=35372?cheap+tramadol">cheap tramadol</a><br><a href="http://forums.ipodhacks.com/member.php?u=35372?buy+tramadol+online">buy tramadol online</a><br><a href="http://www.layersmagazine.com/forum/member.php?u=4313">replica watch</a>

by Yaro on Thursday, July 17th 2008 at 05:57 AM

This shit only works in UTF-8! Fuck!

by Alexander Díaz on Tuesday, July 22nd 2008 at 12:49 PM

Well, actually I manage to make this works with those special characters, Even I use this for sending a mail it quite works.

look at the form here!! www.dmpardo.com

By the way. If you have any inqueries email me!

by cosmin on Wednesday, July 23rd 2008 at 04:29 AM

Hi, i tried your example and it works, but if i put instead of email input, a select with the same name/id it doesn't work, the $_POST['email2'] or $_POST['email'] are BLANK, why ? :|

by dsfdsf on Friday, October 3rd 2008 at 12:31 PM

dfdsfdsf


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs PHP Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons