Saturday, July 4th, 2009

A simple AJAX (JQuery) Contact Form with PHP Validation

by Gabriel on 02/09/08 at 1:06 pm

Save to StumbleUpon Stumble Upon it!     Save to Del.icio.us Save to Del.icio.us    Share on Twitter! Share on Twitter!

Greetings! Subscribe to my RSS feed or get my latest post directly in your mailbox. Thanks for visiting!

The aim of this tutorial is to help you to create a simple (tableless) contact form using AJAX, JQuery & PHP. We will have a HTML page which will contain the form, a CSS file, a php page where the data will be sent and another file where the validation function(s) will be located. JQuery is a new and powerful library which simplifies the way that you write JavaScript.

Step 1 – Creating the configuration file

config.php

<?php
// To
define("WEBMASTER_EMAIL", 'your_name@domain.com');
?>

Here you should fill the e-mail address where you wish to receive the mail as well as the address where you wish to receive the replies (usually the same).

Step 2 – Creating the css file

style.css

/*
Credits: Bit Repository
CSS Library: http://www.bitrepository.com/
*/

html, body  { padding: 0; border: 0px none; }

.notification_error
{
border: 1px solid #A25965;
height: auto;
width: 90%;
padding: 4px;
background: #F8F0F1;
text-align: left;
-moz-border-radius: 5px;
}

.notification_ok
{
border: 1px #567397 solid;
height: auto;
width: 90%
padding: 8px;
background: #f5f9fd;
text-align: center;
-moz-border-radius: 5px;
}

.info_fieldset { -moz-border-radius: 7px; border: 1px #dddddd solid; }

.info_fieldset legend
{
border: 1px #dddddd solid;
color: black; 

font: 13px Verdana;

padding: 2px 5px 2px 5px;
-moz-border-radius: 3px;
}

.button
{
border: 1px solid #999999;
border-top-color: #CCCCCC;
border-left-color: #CCCCCC; 

background: white;

color: #333333; 

font: 11px Verdana, Helvetica, Arial, sans-serif;

-moz-border-radius: 3px;
}

/* Label */
label {width: 140px; padding-left: 20px; margin: 5px; float: left; text-align: left;}

/* Input, Textarea */
input, textarea
{
margin: 5px;
padding: 0px;
float: left;

border: 1px solid #999999;
border-top-color: #CCCCCC;
border-left-color: #CCCCCC; 

color: #333333; 

font: 11px Verdana, Helvetica, Arial, sans-serif;

-moz-border-radius: 3px;
}

/* BR */

br { clear: left; }

Step 3 – Creating the html contact page

This is the page where the AJAX call to contact.php is made. I will explain you the JavaScript Code in detail below:

contact.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>TableLess Ajax Contact Form (Demo)</TITLE>
  <META NAME="Keywords" CONTENT="form, divs">

  <META NAME="Description" CONTENT="A CSS Tableless Ajax Contact Form">

<!-- JQuery -->
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>

 <script type="text/javascript">
   // we will add our javascript code here           

$(document).ready(function(){
$("form").submit(function(){

// 'this' refers to the current submitted form
var str = $(this).serialize();

   $.ajax({
   type: "POST",
   url: "contact.php",
   data: str,
   success: function(msg){

$("#note").ajaxComplete(function(event, request, settings){

if(msg == 'OK') // Message Sent? Show the 'Thank You' message and hide the form
{
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
}
else
{
result = msg;
}

$(this).html(result);

});

}

 });

return false;

});

});

 </script>  

<link rel="stylesheet" type="text/css" href="style.css" />

</HEAD>

 <BODY>

 <center>

<center><h3>A Tableless Contact Form (JQuery & AJAX)</h3></center>

<div align="left" style="width: 500px;">

<fieldset class="info_fieldset"><legend>Contact</legend>

<div id="note"></div>
<div id="fields">

<form action="javascript:alert('success!');">
<label>Name</label><INPUT class="textbox" type="text" name="name" value=""><br />

<label>E-Mail</label><INPUT class="textbox" type="text" name="email" value=""><br />

<label>Subject</label><INPUT class="textbox" type="text" name="subject" value=""><br />

<label>Comments</label><TEXTAREA class="textbox" NAME="message" ROWS="5" COLS="25"></TEXTAREA><br />

<label>&nbsp;</label><INPUT class="button" type="submit" name="submit" value="Send Message">
</form>

</div>

</fieldset>

</div>

 </center>

 </BODY>
</HTML>

Ajax Contact Form

Once the DOM is loaded (we determine this by using $(document).ready()), the script checks if the user submitted the form by using $("form").submit(). If it is, the form elements (names & values) are serialized in order to pass them to the AJAX Call:

var str = $("form").serialize();

$.ajax() takes one argument, an object of key/value pairs, that are used to initalize and handle the request, and returns the XMLHttpRequest object for post-processing (like manual aborting) if needed.

Some options are used to control the behaviour of $.ajax. The information is from JQuery Documentation:

(String) type – This is to determine the type of request that is made: ‘POST’ or ‘GET’. (default is ‘GET’)
(String) url – The URL to request
(Object|String) data – Data to be sent to the server. It is converted to a query string, if not already a string. Is appended to the url for GET-requests. See processData option to prevent this automatic processing.
(Function) success – A function to be called if the request succeeds. The function gets passed one argument: The data returned from the server, formatted according to the ‘dataType’ parameter.

To find out more about $.ajax consider visiting http://docs.jquery.com/API/1.1/AJAX.

The request succeded? In this case we will call the ajaxComplete(callback) function, which executes whenever an AJAX request is completed. The XMLHttpRequest and settings used for that request are passed as arguments to the callback.

If ‘OK’ is returned the form hides and a thank you message is shown. Otherwise, the script will show the errors.

    $.ajax({
    type: "POST",
    url: "contact.php",
    data: str,
    success: function(msg){  

 $("#note").ajaxComplete(function(event, request, settings){  

 if(msg == 'OK') // Message Sent? Show the 'Thank You' message and hide the form
 {
 result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
 $("#fields").hide();
 }
 else
 {
 result = msg;
 }
 $(this).html(result);
 });
 }  

  });

Ajax Contact Form Message Sent

In the next page of our tutorial we will create: functions.php (which has the e-mail address validator) and contact.php (which is the script that parses the submitted data).

Step 4 – Creating the functions’ script.

functions.php

<?php
function ValidateEmail($email)
{
/*
(Name) Letters, Numbers, Dots, Hyphens and Underscores
(@ sign)
(Domain) (with possible subdomain(s) ).
Contains only letters, numbers, dots and hyphens (up to 255 characters)
(. sign)
(Extension) Letters only (up to 10 (can be increased in the future) characters)
*/

$regex = "([a-z0-9_.-]+)". # name

"@". # at

"([a-z0-9.-]+){2,255}". # domain & possibly subdomains

".". # period

"([a-z]+){2,10}"; # domain extension 

$eregi = eregi_replace($regex, '', $email);

return empty($eregi) ? true : false;
}
?>

This file contains only the e-mail address validator, in our sample, but you can use it to add more (validation) functions which can be used in the contact.php page.

Step 5 – Creating the page which parses the data

contact.php

<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/web-programming/ajax/tableless-form-using-jquery.html
*/

include 'config.php';

error_reporting (E_ALL ^ E_NOTICE);

$post = (!empty($_POST)) ? true : false;

if($post)
{
include 'functions.php';

$name = stripslashes($_POST['name']);
$email = $_POST['email'];
$subject = stripslashes($_POST['subject']);
$message = stripslashes(htmlspecialchars($_POST['message']));

$error = '';

// Check name

if(!$name)
{
$error .= 'Please enter your name.';
}

// Check email

if(!$email)
{
$error .= 'Please enter an e-mail address.';
}

if($email && !ValidateEmail($email))
{
$error .= 'Please enter a valid e-mail address.';
}

// Check message (length)

if(!$message || strlen($message) < 15)
{
$error .= "Please enter your message. It should have at least 15 characters.";
}

if(!$error)
{
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
     "From: ".$name." <".$email.">rn"
    ."Reply-To: ".$email."rn"
    ."X-Mailer: PHP/" . phpversion());

if($mail)
{
echo 'OK';
}

}
else
{
echo '<div class="notification_error">'.$error.'</div>';
}

}
?>

In contact.php, we have to determine first if a POST request was sent to the file. If $post is not null, the functions.php file is included (containing the e-mail validator) and the POST fields are declared. Each required field is checked. If any error is found, the $error variable will be filled with that error message. At the end, if $error is null (as it was initially) & the mail is sent, contact.php will output ‘OK’ (which is checked in contact.html). It is is not null, contact.php will output the error(s), which will be shown, of course, in contact.html.

Be notified when we have new posts by subscribing to BitRepository RSS Feed.
Support us!Did you like this post?
Please spread the word!
Save to StumbleUpon  Save to Del.icio.us  Share on Twitter!    

131 Comments

asd

Sep 16th, 2008

a working demo would be nice

Gabriel

Sep 22nd, 2008

Yes, it would be, but the script has the mail() function which can be used abusively (i.e. SPAM). If a demo will be made, it must have some protection.

Gabriel

Sep 29th, 2008

A demo is now available.

Array

Oct 9th, 2008

Thank you very much for your Tutorial. But it has a small Validation error in e-mail field.

info@yahoo,com
i mention comma in the above Email address.. But it doesent validate your code..

plz check and correct it..

Thank you

Gabriel

Oct 10th, 2008

Thanks for noticing. I’ve fixed the error by adding a backslash before the period sign.

pierre

Oct 23rd, 2008

hi, I tried it but it doesn’t work with ie6

Pierre

Oct 23rd, 2008

sorry, I forgot to put my phpserver on,
it’s working well with ie6

Gabriel

Oct 23rd, 2008

Good, I was quite surprised when I read your first comment, because I know that JQuery is compatible with IE6.

[...] Tableless Ajax Contact Form With jQuery (Tutorial & Files) – Demo [...]

[...] Tableless Ajax Contact Form With jQuery | Demo [...]

Jamie

Oct 28th, 2008

How might I get this to put the user’s email into the “from” field properly so that a REPLY goes back to them instead of to me? In my use, this would be considerably more useful. I’ve tried putting $from and $email into the config file, but that doesn’t do it. I don’t know enough about PHP yet.

Gabriel

Oct 29th, 2008

Replace

."Reply-To: ".REPLY_TO."\r\n"

from line 54

with

."Reply-To: ".$email."\r\n"

I’ve also updated the post.

Alex

Nov 3rd, 2008

Hi,

Awesome site, thanks so much!

I’m using your script for an email sign up form. How would I go about forcing an email subject when the user doesn’t have the option of entering a subject.

Thank you so much :)

Gabriel

Nov 4th, 2008

If you don’t need a subject from the person filling the form & want to set a specific subject you can do the following:

1. Remove line 76 from the form (the one with the subject)

<label>Subject</label><INPUT class="textbox" type="text" name="subject" value=""><br />

2. Remove line 19 from contact.php

$subject = stripslashes($_POST['subject']);

3. Change $subject from line 58 (where you have the mail function) with ‘your subject here’.

Jatin Meshiya

Nov 6th, 2008

thanks

praveen

Nov 6th, 2008

hi webmaster, i have downloaded your script but its not working
nothing is happening when i click on submit button
iam using php4 and testing under localhost do i need to change any code if any please post me
thank u

Gabriel

Nov 6th, 2008

What browser are you using (type & version)? Please take a look at this page: http://docs.jquery.com/Browser_Compatibility. Perhaps there’s a compatibility problem between JQuery & your browser. Did you see the demo in action before downloading the files?

Jamie

Nov 8th, 2008

Great! That modification worked without a problem.

Now, I’d like for the person’s name to be put in the From: field properly. They’re typing their name into the form, but I don’t receive it. I did replace $from with $name (I forget where) and it puts it into the proper field… but, it appends @mydomain.com after it. Other than that, this script does exactly what I needed with a minimum of hassle. Thanks a lot!

Gabriel

Nov 8th, 2008

I’ve update the tutorial. Check line 53 from the contact.php page ;)

"From: ".$name." <".$email.">\r\n"

Garry

Nov 11th, 2008

Hi,

This is great website, keep it up :)

I’m just wondering how I would go ahead and force a sentence such as “The following email would like to sign up to the Newsletter” in the body of an email?

Also is it possible to have a checkbox submit a true or false?

Starting to get more in PHP coding… sites like theses are a great help. If there’s anyway I can donate some money for your help, please let me know :)

Thanks.

Gabriel

Nov 12th, 2008

Hi,

Thank you for your comments regarding this website. Let’s add the checkbox first.

1. Here’s the code that should be inserted in contact.html:

<label>Sign up to Newsletter</label><input type="checkbox" name="newsletter_signup"><br />

I recommend you to add it just AFTER:

<label>Comments</label><TEXTAREA class="textbox" NAME="message" ROWS="5" COLS="25"></TEXTAREA><br />

2. Now, we have to edit contact.php. AFTER:

$message = htmlspecialchars($_POST['message']);

add the following line:

$newsletter_signup = $_POST['newsletter_signup'];

3. We will make the final modifications.

Look for:

$mail = mail(WEBMASTER_EMAIL, $subject, $message,
     "From: ".$name." <".$email.">\r\n"
    ."Reply-To: ".$email."\r\n"
    ."X-Mailer: PHP/" . phpversion());

Just BEFORE it add the following code:

if($newsletter_signup)
  {
  $message .= "\n\n"."[The following email would like to sign up to the Newsletter.]";
  }

Notice how I used the string concatenation to add additional text to the message.

I hope you will manage to successfully implement the code I gave you. If you have any questions, let me know.

If you’d like to make a donation, you can look for a PayPal button located just above the pagination links for this tutorial.

Cody

Nov 15th, 2008

Thank you for this great form.

How would you change the submit button so when a user clicks on it, it changes to something like ‘Submitting Form, please wait…” With the dots animated.

Gabriel

Nov 15th, 2008

This form submits fast enough and a loader (until you the script gets a response from ‘contact.php’) is not really needed. However, it can be useful if the user has a slow bandwidth connection. Here’s how you can add one:

1. AFTER:

<INPUT class="button" type="submit" name="submit" value="Send Message">

ADD the following div:

<div id="loading"></div>

2. AFTER:

$("form").submit(function(){

ADD the following code:

$("#submit").hide();
$("#loading").html('Loading...');

This way the submit button is hided and the loader is shown.

3. BEFORE:

$(this).html(result);

ADD:

$("#loading").hide();
$("#submit").show();

The loader is hided and the submit button is restored.

As for the dots you can use an animated GIF:

$("#loading").html('Submitting Form, please wait <img src="path/to/dots.gif" align="absmiddle">');

Cody

Nov 18th, 2008

Thank you, works great!

Jasper

Nov 28th, 2008

Great tutorial! I was wondering if i could send additional information to the email, for example i have a field called “Company” and would like it to be in front of the subject (along with the first- and last name).

Gabriel

Nov 28th, 2008

Do you want to replace the “name” field with 2 fields (first & last name) and to add an additional field called “company”? Would the subject be something like: “Company Name: First Name, Last Name”?

Jasper

Nov 28th, 2008

Yes that’s exactly what i need. Do you know how to do this?

Gabriel

Nov 28th, 2008

Sure, here’s what you have to do:

1. Replace the following line from the contact.html page:

<label>Name</label><INPUT class="textbox" type="text" name="name" value=""><br />

WITH this code::

<label>Company</label><INPUT class="textbox" type="text" name="company" value=""><br />

<label>First Name</label><INPUT class="textbox" type="text" name="first_name" value=""><br />

<label>Last Name</label><INPUT class="textbox" type="text" name="last_name" value=""><br />

2. Now, you have to edit contact.php. Find this line:

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

Replace it with:

$company = stripslashes($_POST['company']);
$first_name = stripslashes($_POST['first_name']);
$last_name = stripslashes($_POST['last_name']);

Find:

if(!$error)
{

AFTER it, ADD:

$subject = $company.': '.$first_name.', '.$last_name.' - '.$subject;

3. Let’s add some validation to the new fields! Find:

// Check name

if(!$name)
{
$error .= 'Please enter your name.';
}

Replace it with:

// Check first name
if(!$first_name)
{
$error .= 'Please enter your first name.';
}  

// Check last name
if(!$last_name)
{
$error .= 'Please enter your last name.';
}  

// Check company
if(!$company)
{
$error .= 'Please enter your company name.';
}

To make a field optional, remove the conditional IF that verifies it.

Jasper

Nov 28th, 2008

Thanks so much! Once again, great tutorial. And the support is awesome :)

Beyblade

Dec 17th, 2008

It doesn’t validate for sub-domain email addresses.

Like my email address:

beyblade[- at -]quickcms [- dot -]exofire[- dot -]net

Gabriel

Dec 17th, 2008

It does now ;-) Thanks for the tip!

Pari

Dec 17th, 2008

Hi,

I just tried it on my website and it seems to be working fine but I am not getting any email :( I have been waiting for the last 30 minutes now. I added my email twice in the config file, is there anyplace else where I need to add it? I had to copy paste the codes into files because my zip extractor wont open the zipped file downloaded from here either :(

Travis O'Donnell

Dec 17th, 2008

For some reason when I am using this on my site, when I press ‘Submit’, js alert window comes up saying ’success!’. But doesn’t do anything after. Also if I remove the [HTML STRIPPED] line it still does nothing.

Pari

Dec 17th, 2008

Oh please disregard the earlier message. I got the email after an hour! Thank you so much for this awesome script!!

Gabriel

Dec 18th, 2008

@Travis O'Donnell: After checking the contact form that you installed in your site, I've noticed that jquery-1.2.6.js is not loaded. Are you sure the file is in the main root of your site? I've tried to open it but I got an error.

Jasper

Dec 23rd, 2008

Thanks for helping me earlier on with the subject field. I was wondering how i could send a overview of all the fields in the email, like:
- Company:
- First name:
- Last name:

Hope you can help me out with this one!

Greetz,
Jasper

Gabriel

Dec 26th, 2008

You need to modify $message. Example:

$message = "- Company". $company."\n- First name: ".$first_name."\n- Last name: ".$last_name."\n\n".$message;

Scott Brooks

Dec 26th, 2008

Nifty! Thanks for the great example!

Imgr8

Dec 27th, 2008

Hi,

I've been trying to make this work for the last two days now and it shows the thank you message but I dont get anything in my email. I tried different email accounts, both yahoo and hotmail. I didnt change any code in either of the pages. Can you look at it and tell me whats wrong if you have time? The link is http://www.ranbirkapoor.net/catb/contact.html

Thanks!

Gabriel

Dec 28th, 2008

This has nothing to do with the script, which is working fine. It's probably a problem with the software that is installed on your server and sends the mails. Did you use mail() before in other scripts? Did it work? Also, make sure that you didn't change the original script and you typed the correct e-mail address in the config.php file.

Madiha

Dec 29th, 2008

This is amazing, just what I needed!! Great job! I had a question… What if I have two forms on my site? One for comments and one for ordering. How can I modify the script so it will work with two different forms with different fields?

Thanks so much!

Gabriel

Dec 30th, 2008

Madiha, good question! I have updated the ZIP file. If you download it, you will find a page sample with 2 forms in the same html page (multiple_forms.html). I will also update this tutorial with an explanation of how you can use more then 1 form in a page.

Madiha

Dec 30th, 2008

Hi sorry but the zip file does not work, it says there are 0 files in the folder…can you please check for me, I am pretty sure its empty…

Thank you so much for ur help!

Gabriel

Dec 30th, 2008

I've just downloaded the ZIP file (21,1 KB) and extracted it successfully. What software are you using to extract the ZIP archive?

Madiha

Dec 30th, 2008

Hi, I am using Z-Zip and I also installed Winzip and winzip error is saying "File corrupt, possible transfer error…"

hmmmm…

Gabriel

Dec 30th, 2008

I will send you the ZIP via e-mail and find a solution for this transfer error problem.

Madiha

Dec 30th, 2008

Thanks alot! It worked great!! This is the best form out there!

I had a quick question about an answer that you posted for somebody here…

The Question was, How do we add Company name, First name, Last name to the email we recieve inside the body of the email?

And you said:

You need to modify $message. Example:

$message = "- Company". $company."\n- First name: ".$first_name."\n- Last name: ".$last_name."\n\n".$message;

But in my contact.php file, I have this info already placed there:

"$message = htmlspecialchars($_POST['message']);"

How do I add that new line in?

Thank you for all your help!

Gabriel

Dec 30th, 2008

Yes, before the line with the mail function add:

$message = "- Company". $company."\n- First name: ".$first_name."\n- Last name: ".$last_name."\n\n".$message;

This way, you will have company, first & last name before the actual message. Notice how I used string concatenation in this situation.

Madiha

Dec 30th, 2008

Hi, thank you that worked!

But now, it wont validate if a message was input and if it was less than 15 char..

It wont give me an error if i enter NO message…

=/

Gabriel

Dec 30th, 2008

Did you remove $message = htmlspecialchars($_POST['message']); ? I said that you should add that new line before the call to mail() function. I don't know how you modified contact.php. The validation should work 100%!

Madiha

Dec 30th, 2008

This is what I have:

$message = "- Name: ".$name."\n- Phone: ".$phone."\n\n".$message; htmlspecialchars($_POST['message']);

Gabriel

Dec 30th, 2008

No, that is wrong! I told you to add the new line before the call to mail() (just after if(!$error) ) without any other changes.

Madiha

Dec 30th, 2008

Ohhh. Im sorry lol. I misunderstood. Okay I tried that now it works!!

=) Thanks alot for all your help!

Jasper

Jan 7th, 2009

That's great! The strange is though i don't see the actual "message".
I do see company, firstname, lastname. What am i doing wrong?

Gabriel

Jan 7th, 2009

I don't know how you edited that file. But if you followed my instructions it should have worked.

Jasper

Jan 8th, 2009

You right, my bad!!

Ted

Jan 17th, 2009

Thank you very much for a clean and thorough presentation!

Just wanted to note I had to change (in contact.php – Line 20):

$message = htmlspecialchars($_POST['message']);

TO:

$message = stripslashes(htmlspecialchars($_POST['message']));

because, for example: "user's typed message" was sending me: "user\'s typed message". I don't know if it is my server's PHP settings (which are default from my provider) or what, but I had to add stripslashes to the $message line, now I am good.

Gabriel

Jan 18th, 2009

Yes, you did good. I just omitted to add it for "message", as I did for "name" and "subject". Will update the post!

Jasper

Jan 19th, 2009

How can i validate a select option?

Jasper

Jan 19th, 2009

This is what i have:

<select name="aanhef" id="aanhef">
<option value="De heer">Man</option>
<option value="Mevrouw">Vrouw</option>
</select>

And i can't send the form because the select field is empty.
Can you please help me out?

Jasper

Jan 20th, 2009

Fixed the problem i guess , sorry!

Gabriel

Jan 20th, 2009

@Jasper: That dropdown ("aanher") doesn't really need a validator because there are only 2 options in it and none of it is NULL.

Jasper

Jan 20th, 2009

Could i add a CC adres so that it mails to 2 adresses?

Jasper

Jan 20th, 2009

Or can i just ad an (comma seperated) address in the config.php

Gabriel

Jan 22nd, 2009

Yes, you can either use CC or call again mail():

$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());

$mail_two = mail('your_second_mail@domain.com', $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());

I do not recommend adding new email address separated by commas in the config.php. Everyone who receives the mail will see all the addresses where the mail was sent and in many cases this is not recommended at all.

Ted

Jan 24th, 2009

Cool.

I've been running this past a page with other Ajax calls, and once msg=='OK', the .ajaxComplete reacts to the successful completions of the other, unrelated Ajax events.

So, in contact.html:

27 $("#note").ajaxComplete(function(event, request, settings){
39 $(this).html(result);

…do you see any problem with eliminating line 27 and changing line 39 to this?:

39 $("#note").html(result);

Just curious, because I made that change and everything is still working in what I've checked: Safari 3.x, FF3, and IE7.

Jasper

Jan 27th, 2009

Oke that's cool. So can i send the second mail to the person who filled in the form? I'm not sure how to edit this:
$mail_two = mail('your_second_mail@domain.com', $subject, $message,

Is it something like this?
$mail_two = mail(". $email.", $subject, $message,

Hope you can help me!

gisele

Feb 1st, 2009

hi

i add succesfull your ajax form to my website but i have 2 issues

1 html specialchars are not suportet when i receive a mail it remove all special chars like àáâãäçèéêëìíñòóôõö how i can solve this

2 the second is in the emails is nothing like name phone adress ect

this 2 issues also dont work in your downloadarchive i test it can you help me please thank you

[...] Tableless Ajax Contact Form With jQuery (Tutorial &amp; Files) – Demo [...]

Gabriel

Feb 2nd, 2009

@Jasper: To send a mail to the person who filled the form consider using the following code:

$mail_two = mail($email, $subject, $message,
"From: your_name < ".WEBMASTER_EMAIL.">\r\n"
."Reply-To: ".WEBMASTER_EMAIL."\r\n"
."X-Mailer: PHP/" . phpversion());

Gabriel

Feb 2nd, 2009

@Ted: It shouldn't be a problem. It's good that you solved the issue by making this change.

Jasper

Feb 3rd, 2009

Thanks a lot! That works fine!
Just for the record, i donated a little bit :)

gisele

Feb 3rd, 2009

i fixed by myself and add few functions

captcha enable disable in config.php
additional fields enable disable in config.php
autoresponder defne text in contact.php
add body text for received emails
fix for suport html special chars is working now
name
phone
adress ect.
ALL THIS CHANGES only for the contact formular not for the feedback
download here http://www.jobadoo.us/contact_form1.rar

Jasper

Feb 4th, 2009

In the second email i don't want the same information as the first email.
The second email is sent to the person who fills in the form and should therefore contain a text message instead of all the filled in information.
But i'm not sure how to do this.

$mail_two = mail($email, $subject, $message,

so the field $message should be replaced with a text.

joe

Feb 4th, 2009

i followed the steps correctly (or at least i think i did)

it looks good up till the end, when you click the submit button, this error appears above

\r\n" ."Reply-To: ".$email."\r\n" ."X-Mailer: PHP/" . phpversion()); if($mail) { echo 'OK'; } } else { echo '
'.$error.'

Jasper

Feb 6th, 2009

No worries! Allready fixed it!
I just added a second $message

Mihai Bocsaru

Feb 12th, 2009

Excellent facility! I'm using AJAX contact forms for over 2 years, but I would like to either integrate JQuery within my current version or use other solutions like this one.

A bug I've discovered with your solution is that it reports some legitimate email addresses like invalid ones

For instance, my email address ends in [at] pro-it-service.com

The script seems to not recognize the dashes from the domain name…

Kind Regards,
Mihai Bocsaru

Gabriel

Feb 13th, 2009

Thanks for letting me know about this bug. I've removed it by updating the e-mail validator function.

Mihai Bocsaru

Feb 13th, 2009

It's a pleasure and actually, thank you for such an excellent job!

Mihai Bocsaru

Feb 13th, 2009

I guess you've updated it on your end, but didn't update it online as well or on the downloadable archive… I've just looked at the coding from this page and inside the archive and the email validating function is the same…

Gabriel

Feb 13th, 2009

I did update it online (tutorial & demo). I've also updated the ZIP archive. It should work now. I will re-upload the files again.

Mihai Bocsaru

Feb 15th, 2009

Great, thank you! I've just discovered now that it is not compatible with Lightbox2 from http://www.lokeshdhakar.com/projects/lightbox2/

In case you place the lightbox 3 js calls before your ajax form js coding, then the ajax form will work, but the lightbox not and vice versa…

If you have the 3 lightbox js files referenced after the js coding for your ajax form, then the lightbox effect will work, but not your form AJAX effect…

Can you please try, see and fix that?

Cheers,
Mihai

Gabriel

Feb 15th, 2009

Lightbox2 is using Prototype Framework & Scriptaculous Effects Library. My form uses JQuery. You need to make this library compatible with other frameworks. Here's a URL that will help you: http://docs.jquery.com/Using_jQuery_with_Other_Libraries

Mihai Bocsaru

Feb 15th, 2009

Excellent support! The process seems quite straight forward on http://docs.jquery.com/Using_jQuery_with_Other_Libraries

Mihai Bocsaru

Feb 15th, 2009

Actually, I've thought about having both features on the same technology and so I've searched for Lightbox based on jQuery.

After some testing the best solution for me is http://plugins.jquery.com/project/jquerylightbox_bal because I could keep referencing images where I want the lightbox effect with rel="lightbox" ;)

So folks, if you want to operate Lightbox and this awesome ajax form, consider http://plugins.jquery.com/project/jquerylightbox_bal instead of http://www.lokeshdhakar.com/projects/lightbox2/

I've used Lokesh Lightbox2 solution for 2 years, but it's now time to switch over to jQuery

hqkqn

Feb 15th, 2009

Thank's…..

deviantz

Feb 25th, 2009

This is a nice article!
Thanks for sharing this.. keep it up!

AndrewP

Mar 3rd, 2009

Great form with validation!

One question, if I wanted to validate a field for phone, where would i add this?

thanks!

Bingeboy

Mar 4th, 2009

Great job!

IASIIS

Mar 4th, 2009

Hello. Amazing tutorial and amazing webmaster response here!

I’m a novice and have probably what is a basic question. Why this html code is included:

69. <div id="note"></div>
70. <div id="fields">

Because I do not see the ids #note and #fields in the CSS code.

Later :)

TommyB

Mar 9th, 2009

Gabriel, awsome tutorial. I used your method on a site over the weekend and it is working well, so thank you. Just a thought/question…Would it be worth validating the form fields with jQuery as well as in the php file? That way the data will be validated even quicker. Let me know your thoughts.

Tom

Gabriel

Mar 10th, 2009

The ID attribute is used to assign a unique identifier to an element. For instance “note” is assigned to a DIV where the submit status is shown (errors or message sent). If you study the JavaScript code you will see how ‘#note’ is used.

IASIIS

Mar 10th, 2009

Ahh yes. With out that code it will not print out the Ok and Error messages. Thank you for your help Gabriel.

IASIIS

Mar 10th, 2009

There are 3 error messages that can be displayed. I want to have a different div for each of the messages instead of the one “.notification_error” div. I would need:

- .notification_name_error
- .notification_email_error
- .notification_message_error

how would I go about programming the java to allow this to occur?

Also have another question for you.

SCENARIO 1
also, lets say that someone screws up all 3 required fields and gets all 3 errors. I would like these errors to be displayed in their individual rectangular sausage shaped divs starting with

1) “.notification_name_error” at the top place
2) “.notification_email_error” in the middle
3) “.notification_message_error” on the bottom

SCENARIO 2
What if someone only screws up the email and the message fields. In that case I would want the “.notification_email_error” and “.notification_message_error” divs to appear but I would want the “.notification_email_error” div to appear in the top placement just like the “.notification_name_error” div in Scenario 1. The “.notification_message_error” div would appear in the 2nd, or middle, placement just like the “.notification_email_error” div in Scenario 1.

SCENARIO 3
If someone screws up just the message field then I would want the “.notification_message_error” to appear in the top placement just like the “.notification_name_error” div in Scenario 1.

How would one go about programming the java to attain this result?

Thanks again Gabriel,
IASIIS

Black Shark Media

Mar 15th, 2009

Thanks for this great script.
I’ve implemented on a site that has more fields (12 in total), Name, Telephone and Email are required and the rest are not.
The problem appears when I complete only one field(and the error appears), then I complete the rest of the required fields but the submit button is disabled(doesn’t function anymore)
Also the email and telephone insert validation doesn’t seems to be working in my multiple field form(the same check functions gives me error as the field is not completed when in fact it is completed!
Any ideas? Thanks

easy rebel

Mar 16th, 2009

Hey, thanks a lot for this. I’ve been learning a lot about jQuery lately, and this was great.

I’m running into a problem with this however. Everything works fine except that when the message sends/returns successfully. The only thing that doesn’t is the success message.

The success message doesn’t appear and the fields div doesn’t get removed after a successful submission. It seems to just skip to the next code block in the javascript and returns/prints the ‘OK’ result from the php script instead of reading it correctly and changing content.

I was using jQuery 1.3.1, then switched to 1.2.6 just to see if that was the issue and I ran into the same problem.

Any help would be appreciated. Thanks!

jamie

Mar 16th, 2009

Hi thanks for the form, this is the first time adding this to a site. I have an issue however, when i click submit all that happens is that instead of contact (at the top of the form) i get “OK” displayed and all the data in the form remains. Maybe i have done something wrong?

Thanks
Jamie

Gabriel

Mar 17th, 2009

What you want is something quite different than what you currently have. First, you need to add the DIVs (with no text inside them) in the form (top, middle, bottom), each having a unique ID and the style set to ‘display: none’. You also need to change the contact.php file to send the response in JSON format. The JavaScript receives the data from contact.php and checks (for instance) if the email error notification exists. If the ‘email’ object exists, then set the notification_email_error to “visible” mode and fill the text error in it. I don’t know how familiar you are with PHP, JQuery and JSON but here are some URLs that can help you:

http://www.json.org/
http://www.php.net/json
http://docs.jquery.com/Events (JavaScript Events)
http://docs.jquery.com/Selectors (JQuery Selectors)

Gabriel

Mar 17th, 2009

Did you change anything in the original code? Is the demo from Bit Repository working fine for you?

Gabriel

Mar 17th, 2009

I think you have modified contact.php. Did you add HTML code in it? The only thing that should be outputted from contact.php is “OK” (if successful).

easy rebel

Mar 17th, 2009

Gab, thanks for the response. Yes, I changed some code in the contact.php file because I needed to make some changes to integrate into my own setup. Nothing major. I’ve looked it over multiple times and didn’t see anything that could be causing an issue like this.

I did download the tutorial files and try them and they worked fine. Looking over those and this tutorial, there are a few differences in some of the coding. So, I’m going to use the downloaded files as a guide to redo some things and see if I can fix this.

easy rebel

Mar 17th, 2009

Ok, I’ve narrowed things down to the only thing that can be causing this issue.

Smarty!

There’s an issue with the Smarty templating system and your script that I need to figure out. If I take the success from the javascript and use that as the echo string instead of ‘OK’ in the contact php file, it will return that success div without any issues. That’s the quick fix, but the problem with that is the fields div doesn’t get removed. Not that big of a deal, but sort of unprofessional, especially since the data in the input fields are still there after a successful submission.

It seems as if the ‘OK’ echo string thats returned on success isn’t interpreted correctly by Smarty. Since it displays that echo string, I guess it takes it as a literal character. I tried taking the JS for this and putting it in an external JS file and linking to it in the header, but that didn’t change anything. Maybe I need to assign the return value as a smarty variable and then pass that to the JS somewhow. Bleh. :P

IASIIS

Mar 20th, 2009

Hey Gabriel,

Thanks for that info but I think it will take me some time to learn how to utilize JSON to reach the previously stated goal.

On another note, I have made some cosmetic changes to the contact form on my site. One of them was adding a 110 pixel wide background image (which contains a 55pix wide a:link state and a 55pix wide a:hover state) to the button div. I would like to create a rollover version so when someone is hovering over the button div the background image position will shift left by 55 pixels which will revealing the a:hover part of the image.

Some one from another forum suggested implementing JQuery event handlers that would be able to shift the background but, since I am a beginner I haven’t a clue how to work them in.

One other change I made was getting rid of the text which appeared next to each text fields. Instead I placed them inside each of the text fields so when the form loads you will see “name”,”email”, “subject” appear inside their related text fields. I can not get it so that the word “message” appears inside of the message div.

Any ideas on how to solve these two problems?

Here is the link to my contact form page:

http://caeious.com/stomatologdeblin/kontakt.htm

P.S. I have had to translate the OK and Error messages as well as “name”,”email”,”subject” into the Polish language so it may seem a bit strange but the form layout is structurally the same as you have in the tutorial. With Firebug you can see all the code. If you don’t have Firebug then I will post the code if you need it.

Thanks and take care,
IASIIS

Jitendra Vyas

Apr 15th, 2009

is it must to have a mail account on our own domain to use this script. can i get all mail through this form on my free gmail(not gmail apps) account

RichardF

Apr 16th, 2009

Hi, great script got it working no problem. Just 1 quick question: I want to use the form as a kinda reservation form so I have added a drop down list of dates for the user to select. It doesn’t have to be validated, but I would like it to show up in the email. How do I get non-validated fields to be shown on the sent email?

Ta

Houssam Ballout

Apr 21st, 2009

Hello,
Thanks a lot for this great tutorial, I was wondering, if I can use 2 forms on the same web page?
thanks in advance

Jasper

Apr 23rd, 2009

Does anyone know how to attach and send a jpg file with the form?

Richard Neill

Apr 24th, 2009

thanks a mil for this, works a charm!

Gabriel

Apr 24th, 2009

This topic was discussed before. In the zip archive containing the tutorial’s files you can find multiple_forms.html which has 2 forms in it. This way you will see how multiple forms can be added in the same page.

Houssam Ballout

Apr 24th, 2009

Thanks I didn’t watch it

Brian Sahagun

Apr 25th, 2009

ADD:
$(”#loading”).show();

BEFORE:
$(”#submit”).hide();

So everytime you press Submit, the loading message will appear.

- In response to Gabriel’s “Adding a loading message” entry on Nov 15th, 2008.

Jasper

May 7th, 2009

I’m having a hard time trying to implement this function http://www.americanfinancing.net/email-image-upload.cfm into the form. Does anyone have experience with this?

Tom

May 8th, 2009

This form is great, and exactly what I was looking for.

However, I just noticed, that when someone attempts to use the search form in my sidebar, instead of searching, it submits the e-mail form (which then produces error messages because the e-mail fields weren’t filled out).

How do I keep it from conflicting with my search form submissions?

Tom

May 9th, 2009

Nevermind. Figured it out. Feeling really stupid.

deviantz

May 11th, 2009

Hello, this for the updates all question you answer to this page..

I just have a basic question.. I have 2 forms in one page using this script. the problem, i think when I click to submit the other one. the error msg will show on the first form I have.

pls let me know what i need to do with this..

Thanks and more power!

deviantz

May 11th, 2009

Hello one more thing. do you have a credit card validation and phone number function of this script? pls can i have it?? thanks a lot for the help!

deviantz

May 11th, 2009

hi pls ignore my 1st question.. I just read the comment and I will download your latest file.

I think this is the only I need if this is possible..

how can add a credit card and phone number validation function of this script?

thx!

Brian

May 11th, 2009

Hey Gabriel, awesome script BUT I have one problem, can you help?

When I receive my email after entering the info, ONLY the “message” is in the body of the email and it appears in the subject line of the email…

Is it possible for the email to have this data…

Subject line in email inbox “A user at yoursite has sent an email”

Body info in email:

Name: users name
Email: users email addy
Subject subject user entered
Message: message user entered

is this possible with this script?

Gabriel

May 12th, 2009

Brian, consider checking the previous comments from this post and you will find the solution ;-)

stuart

May 13th, 2009

Thanks for your great bit of code.

When I try to navigate away form the page where the form is displayed before entering any data, “This field is required” is displayed on one of the input boxes and the page remains displayed.

Elliot

May 14th, 2009

Hey Gabriel,

Fantastic article, very insightful and well laid out. I have tried to implement this on my own website but unfortunately I never receive the email.. The form itself works perfectly, if the correct information isn’t present it doesn’t validate and if the correct information is present it hides the form and displays a success message, yet I never receive an email. I have tried the mail() function before and I know that my host supports it so I’m truly stumped on why it isn’t working. Perhaps you can find the problem?

Best regards,
Elliot

Elliot

May 14th, 2009

Hey Gabriel,

I seemed to have solved the problem, sorry to waste your time!!

Unfortunately I still have one other problem. With my website, I dynamically load in content using jQuery and AJAX. The only problem with this, is when I load in the content, in this case the contact form, it’s loaded after the DOM has been initialized. To fix this on other pages (let’s say where I’m using lightbox) I simply reinitialized that code but with your code I’m not sure how to accomplish this. Any chance you can help?

Best regards,
Elliot

Elliot

May 14th, 2009

My final post so as not to spam your forums :)

I figured out how to reinitialize the form and in the process may have further advanced your script, I’ll leave that judgement upto you. I’ve condensed your code into 2 files, 1 JS and 1 PHP. The code looks like this:

JS:
$(document).ready(function() {
$(”form”).live(”submit”, function() { var str = $(this).serialize(); $.ajax({
type: “POST”,
url: “scripts/contact.php”,
data: str,
success: function(msg) {
$(”#note”).ajaxComplete(function(event, request, settings){
if(msg == ‘OK’) {
result = ‘Your message has been submitted, thank you!’;
$(”#fields”).slideUp(500);
} else { result = msg; }

$(this).html(result);
});
}
}); return false; });
});

PHP:
<?php

/* Credits: Bit Repository */

define(”WEBMASTER_EMAIL”, ‘YOUR@EMAIL.COM’);
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;

if($post) {

function ValidateEmail($email) {
$regex = “([a-z0-9_.-]+)”. # name
“@”. # at
“([a-z0-9.-]+){2,255}”. # domain & possibly subdomains
“.”. # period
“([a-z]+){2,10}”; # domain extension
$eregi = eregi_replace($regex, ”, $email);

return empty($eregi) ? true : false;
}

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

$error = ”;

if(!$name) { $error .= ‘Please provide a name you wish to be addressed by. ‘; }
if(!$email) { $error .= ‘Please enter an email address. ‘; }
if($email && !ValidateEmail($email)) { $error .= ‘Please enter a VALID email address. ‘; }
if(!$message || strlen($message) < 10) { $error .= “Please enter a message [10 characters min.]. “; }

if(!$error) {
$mail = mail(WEBMASTER_EMAIL, ‘[Contact @ebarer]‘, $message,
“From: “.$name.” \r\n”
.”Reply-To: “.$email.”\r\n”
.”X-Mailer: PHP/” . phpversion());

if($mail) { echo ‘OK’; }
} else { echo ”.$error.”; }
}
?>

Cheers,
Elliot

Christian

May 24th, 2009

Hi, is it possible to clear the form fields if successful as well as display the success message?

Scott

May 28th, 2009

Hi, is there a way to consolidate the contact.html and contact.php files into one page?

Im trying to make the form work all as one page if possible. (I’ve already put the config.php and functions.php code into contact.php)

Great form though either way!

Thanks,

Scott.

Scott

May 28th, 2009

Sorry, disregard the above, I now understand AJAX a bit better!

Lol.

-Scott.

George

Jun 1st, 2009

Hi,
Can anyone tell me what to do to add a checkbox that if checked to send a copy of own message to the email user enters?

Thank you.

John

Jun 1st, 2009

Hello. Any clue as to why my email sends but the “Thank you” message does not? Its just showing the form.

David

Jun 12th, 2009

Thanks! Great Job!

prady

Jun 18th, 2009

Hi,

I always get an alert saying “success” everytime i click the submit button.
What am i doing wrong??
Pls help

prady

Jun 18th, 2009

I figured that out. I didnt up the jquery-1.2.6.min.js.
I would like the form not dissapearing.Just the message coming in and after sometime it fading away
How can we do it?
Thanks
Prady

Leave a Comment