Vous êtes sur la page 1sur 20

1/20 www.elated.

com/articles/slick-ajax-contact-form-jquery-php/
Advertise Here
Current forum topics
Web design state of the nation: one designer's
journey
Build Responsive Sites Quickly with Foundation
JavaScript Tabs - Create Tabbed Web Pages
Easily
CSS Floats
What would you like to see on elated.com?
Got a question about making a website? Ask it in
the forums we'd love to help you. All questions
answered!
Popular articles
jQuery Mobile: What Can It Do for You?
JavaScript Tabs - Create Tabbed Web Pages
Easily
How to Make a Slick Ajax Contact Form with
jQuery and PHP
Making CSS Rollover Buttons
Object-Oriented PHP for Absolute Beginners
Building a site? We' re here to
help!
At Elated you'll find lots of free webmaster
resources to improve your sites, including:
Web design and development articles and
tutorials
Free website templates
Search articles...

Articles Articles Web Templates Web Templates Stock Images Stock Images Photoshop Actions Photoshop Actions Forums Forums
View Demo Download Code
Tweet Tweet
83
Home : Articles : How to Make a Slick Ajax Contact Form with jQuery and PHP
How to Make a Slick Ajax Contact Form
with jQuery and PHP
Tutorial by Matt Doyle | Level: Intermediate | Published on 1 April 2011
This tutorial shows you how to build a nice-looking, smooth
contact form that visitors can use without having to leave the page
they're reading.
Contact forms can be useful way for visitors to contact the owner of a site. They're easy
to use, and since they don't expose the site owner's email address in the page, they cut
down on spam too.
However, contact forms can also be cumbersome, especially as they're usually on a
separate page. The visitor has to visit the contact form page, fill in the details, view yet
another response page, and then try to make their way back to the page they were
originally reading.
Fortunately, Ajax gives us a way round this problem. By embedding the form in the
page, and submitting the form data via Ajax, the user never has to leave the current
page. It also provides a smoother experience for the user.
In this tutorial we'll build a nice-looking, embedded Ajax contact form that the user can
summon up by clicking a link in the page. Along the way, we'll explore various topics,
Categories: Web Development > PHP
Web Development > JavaScript > jQuery
2/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
Free images
Photoshop actions
Helpful experts in our webmaster forums
A free newsletter packed with useful tips and
advice
Yes, this stuff is free! We just ask that you give us a
link - find out how to link to us. (Note: all our
content is copyrighted; please read our website's
terms of use.)
Never made a website before? Read How to Make
a Website.
including:
HTML5 form fields
How to use fallback techniques to make the form function even if the browser has
JavaScript turned off
Using CSS techniques to create attractive forms
Writing a secure form mailer using PHP
Animating page elements with jQuery, and, of course...
Using jQuery to make Ajax requests
Before you begin, check out the finished product by clicking the View Demo button
above. This opens a new page with some dummy content, and a couple of "Send us an
email" links. Click one of these links to display the form.
The demo doesn't actually send an email anywhere, but the finished code in the
download is fully functional. To get the code, click the Download Code button
above.
Ready? Let's get started!
6 WH S & UH D WH WK H P D UN X S
Let's start with the HTML for our page. This includes the form itself we'll hide it
initially using JavaScript when the page loads and also some dummy content and a
couple of "Send us an email" links that will display the form when clicked:
3/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
I've omitted the dummy content in the above code, since it's not relevant to the
tutorial.
The form sends its data to a processForm.php script that does the actual emailing.
(We'll write this PHP script in a moment.) By setting the form's action attribute to
"processForm.php", we ensure that the form is usable even with JavaScript disabled.
Later, our JavaScript will read this action attribute so that it knows where to send the
Ajax request.
The form itself uses some HTML5 form features such as placeholders, the email field
type, and the required attribute to ensure that all the fields have been filled in. We'll
also add JavaScript validation for browsers that don't yet support HTML5 validation.
6 WH S $ G G WK H & 6 6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!doctype html>
<html lang="en">
<head>

<title>A Slick Ajax Contact Form with jQuery and PHP</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

</head>
<body>

<div id="content">

<p style="padding-bottom: 50px; font-weight: bold; text-align: center;"><a

<!-- Content here -->

<p style="padding-top: 50px; font-weight: bold; text-align: center;"><a href

</div>

<form id="contactForm" action="processForm.php" method="post">

<h2>Send us an email...</h2>

<ul>

<li>
<label for="senderName">Your Name</label>
<input type="text" name="senderName" id="senderName" placeholder="Please type your name"
4/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
Now we'll add the CSS to our HTML page in order to style the page and form. The bulk
of the CSS positions the form and status messages in the centre of the window, and
styles the form and form fields.
Let's look at some interesting sections of the CSS:
1. Style for the contact form and status messages
We give the form and status boxes a nice gentle top-to-bottom gradient using -
webkit-gradient and -moz-linear-gradient, and we also add a drop shadow with
box-shadow (and its vendor-specific variants). Finally, we give the form and
message boxes an opacity of .95 (95%), which makes the page content just show
through a nice subtle effect.
2. Position the form in the middle of the window ( if JavaScript is enabled)
Initially, we simply place the form inline after the page content. This is so that the
form can be used for non-JavaScript-enabled browsers without getting in the way of
the content. However, for JavaScript browsers, we want the form to appear in the
centre of the window, over the top of the content.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<style type="text/css">


/* Add some margin to the page and set a default font and colour */

body {
margin: 30px;
font-family: "Georgia", serif;
line-height: 1.8em;
color: #333;
}


/* Set the content dimensions */

#content {
width: 800px;
padding: 50px;
margin: 0 auto;
display: block;
font-size: 1.2em;
}

#content h2 {
line-height: 1.5em;
}


/* Add curved borders to various elements */
5/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
Our #contactForm.positioned rule does just that. It uses fixed positioning, sets
the top, bottom, left and right values all to zero, and ensures that all 4 margins
are set to auto. This centres the element both horizontally and vertically in most
modern browsers. Later we'll use our JavaScript to add the positioned class to the
form.
We also position the status message boxes in the same way.
3. The header at the top of the form
Our form includes a nice "Send us an email..." header with an image of a postage
stamp. Our #contactForm h2 rule styles this header. We give the text a large italic
style and space the letters out slightly. We also add margin and padding to create
space around and inside the header. We use some negative left margin (-.75em) on
the header to bypass the padding on the form, so that the header goes right to the
left edge of the form. We also set the width of the header to 19.5em so that it exactly
matches the width of the form.
Why -.75em and 19.5em? Because ems cascade, and we've set our font size to
2em. So -.75em actually becomes -1.5em (the width of the form's padding), and
19.5em becomes 39em (the width of the form, minus 1em for the h2's padding).
Phew! Maybe I'll use pixels next time... :)
We also set the heading's colour, give it a dark background, position the postage
stamp image in the top right corner, add a thin bottom border, and add curved top
corners.
4. The fields
We give the input and textarea fields an attractive font, a rounded border using
border-radius, and a gentle inner shadow using box-shadow. We also float the
field labels left so that they sit alongside the fields. When a field is focused (clicked
on or moved to with the Tab key), we give it a blue border and remove the shadow.
We also set outline: none to remove the blue outline added by some browsers.
Finally, we use the :valid pseudo-class to give correctly completed fields a green
background, for those browsers that support HTML5 form validation.
5. The Send and Cancel buttons
input[type="submit"] selects the Send Email button, while
input[type="button"] selects the Cancel button. We float them right to position
them side by side, and add some margin to give them space. We give them a fixed
width, and some padding to make them a decent size. We add a rounded border and
subtle drop shadow, and specify text and background colours. We also make the
buttons slightly transparent ( opacity: .7), and make them fully transparent when
hovered over to highlight them. We use a CSS transition to fade the opacity slowly.
Finally, when the buttons are clicked ( :active) we move the shadow inside the
buttons to give a "pressed" appearance, and give them a black-on-white colour
scheme.
6 WH S % X LOG WK H 3 + 3 I R UP P D LOH U
We've now created our form page, and styled the form. The next step is to build a short
PHP script to actually send the email messages. This script will reside on the web server.
When the user submits the form, the form's data is sent to the PHP script, which then
sends the email and returns a response indicating whether or not the email was sent
6/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
successfully.
Here's the PHP script call it processForm.php, and save it in the same folder as the
form page you created in Steps 1 and 2:
This script is fairly straightforward. Let's break it down:
1. Define some constants
First we define some config options for the name and email address of the person
who will receive the email message. (Change these to your own name and email
address.) We also set a subject for the message.
2. Read the form values
Next we check for our 3 form fields, senderName, senderEmail and message, in the
posted form data. For each field, we check if it exists. If it does then we pass its value
through a regular expression to remove any potentially malicious characters that a
spammer might try to use, and store the result in a variable. If it doesn't exist then
we set the variable to an empty value.
3. If all values exist, send the email
If the 3 field values all contain data then we send the email. First we construct the
recipient string from the recipient name and email address. Then we add a "From:"
header to the message using the name and email address that the visitor entered in
the form. This is the "From:" value that the recipient will see in their email program.
Finally, we use the PHP mail() function to send the email message, storing the
return value in the variable $success. ( mail() returns true if it managed to send
the email, or false otherwise.)
4. Return an appropriate response to the browser
Once we've attempted to send the email, we send a "success" or "error" message
back to the browser as appropriate. If the request URL contained an "ajax"
parameter then we know the form was submitted via Ajax using our JavaScript code,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php

// Define some constants
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "john@example.com" );
define( "EMAIL_SUBJECT", "Visitor Message" );

// Read the form values
$success = false;
$senderName = isset( $_POST['senderName'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/"
$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/"
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/"

// If all values exist, send the email
if ( $senderName && $senderEmail && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}

// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
} else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
7/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
so we simply return the value "success" or "error" to the JavaScript, which will
then display an appropriate message to the user. However, if the form was
submitted without using Ajax then the user must have JavaScript turned off in their
browser. In this situation, we display a more helpful error message in the browser,
with instructions to the user to use their Back button to return to the page.
Our JavaScript will add the ajax parameter to the URL when it submits the form,
as you'll see in Step 6.
6 WH S , Q F OX G H WK H M4 X H U\ OLE UD U\ D Q G VH W WK H
G H OD \
Our form is actually functional now. You can open the page in a browser, click the
"Send us an email" link to jump to the form, fill in the fields, and submit the form to
send the message.
However, we're now going to enhance our form using JavaScript to make the
experience nicer for the user.
We'll use jQuery to do most of the heavy lifting, so the first step is to include the jQuery
library in the page's head element:
Here we've linked directly to the jQuery library on Google's CDN, but you can
download the library and host it on your own server if you prefer.
We'll also add a global config variable, messageDelay, to control how long the message
boxes appear on the screen. This value is in milliseconds. Feel free to change it to a
shorter or longer time:
6 WH S : ULWH WK H init() I X Q F WLR Q
The first stage of our form-enhancing JavaScript is the init() function. This sets up
the form so that it can be shown and hidden on demand, and also modifies the form so
that it will be submitted using our JavaScript, rather than sent natively by the browser.
Here's the code:
1 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
1
2
3
<script type="text/javascript">

var messageDelay = 2000; // How long to display status messages (in milliseconds)
8/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
Let's look at each chunk of the above code:
1. Init the form once the document is ready
We use the jQuery object, $, to trigger our init() function once the DOM is ready.
2. Hide the form, set the submit handler, and position the form
The first thing we do inside the init() function itself is make some changes to our
form, #contactForm.
First we hide it from the page using the jQuery hide() method. Then we set its
submit event handler to our submitForm() function (which we'll write in a
moment). This ensures that, when the user submits the form, submitForm() is
called instead of the native browser form submission kicking in. Finally, we add the
positioned CSS class to the form to reposition it in the centre of the browser
window.
3. Make the "Send us an email" links open the form
Next we bind an anonymous event handler function to the "Send us an email" links'
click events. This function fades out the page content so it's only just visible in the
background; fades the contact form in; and sets the focus on the "Your Name" field,
ready for the user to start filling in the form. Finally, the function returns false to
prevent the links from being followed.
4. When the "Cancel" button is clicked, close the form
Now we bind another anonymous function to the "Cancel" button's click event, so
that the user can close the form by clicking the button. The function simply fades the
form out, and fades the page content back in.
5. When the "Escape" key is pressed, close the form
Similarly we bind a function to the contact form's keydown event, so that we can
read any key the user presses when they're viewing the form. In this function, we
check if the user has pressed the "Escape" key (character code: 27). If they have then
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Init the form once the document is ready
$( init );


// Initialize the form

function init() {

// Hide the form initially.
// Make submitForm() the forms submit handler.
// Position the form so it sits in the centre of the browser window.
$('#contactForm').hide().submit( submitForm ).addClass( 'positioned' );

// When the "Send us an email" link is clicked:
// 1. Fade the content out
// 2. Display the form
// 3. Move focus to the first field
// 4. Prevent the link being followed

$('a[href="#contactForm"]').click( function() {
$('#content').fadeTo( 'slow', .2 );
$('#contactForm').fadeIn( 'slow', function() {
$('#senderName').focus();
} )

return false;
} );

// When the "Cancel" button is clicked, close the form
$('#cancel').click( function() {
9/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
we close the form by fading it out, and fading the content in.
6 WH S : ULWH WK H submitForm() I X Q F WLR Q
We've now set up our form so that, rather than being submitted in the usual fashion, it
will trigger the submitForm() function when the user submits it. This function needs to
do some validation and, if all is well, submit the form data to the PHP script via Ajax.
Here's the function in full:
Here's how the function works:
1. Store the contact form in a variable
Since we'll be using it a lot throughout the function, we start off by storing the
contact form element in a contactForm variable. This element is available to our
function as the this variable, since the function is the event handler for the
element's submit event. We wrap the element in a jQuery object to make it easier to
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Submit the form via Ajax

function submitForm() {
var contactForm = $(this);

// Are all the fields filled in?

if ( !$('#senderName').val() || !$('#senderEmail').val() || !$('#message').val() ) {

// No; display a warning message and return to the form
$('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut();
contactForm.fadeOut().delay(messageDelay).fadeIn();

} else {

// Yes; submit the form to the PHP script via Ajax

$('#sendingMessage').fadeIn();
contactForm.fadeOut();

$.ajax( {
url: contactForm.attr( 'action' ) + "?ajax=true",
type: contactForm.attr( 'method' ),
data: contactForm.serialize(),
success: submitFinished
} );
}

// Prevent the default form submission occurring
10/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
url The URL to send the form to. We grab this from the
form's action attribute, and append an
ajax=true parameter to the query string so that
our PHP script knows the form was sent via Ajax,
rather than via the usual method.
type The type of request to make ( "POST" or "GET").
We grab this from the form's method attribute,
which in this case is set to "POST".
data The data to send with the request. For this, we call
the jQuery serialize() method on the contact
form object. This method takes all the field names
and values in the form and encodes the data in a
query string. We then pass this string to the
ajax() method so it can send the data to the PHP
script.
success This is a callback function that will be called once
the Ajax request has finished and the browser has
received the response from the server. We set this
to our submitFinished() function, which we'll
write in a moment.
work with.
2. Check all the fields are filled in
Now we check that each field's value is not empty by using the jQuery val() method
on each field.
3. Display a warning if the form isn't completed
If 1 or more of the fields are empty, we fade out the form, then fade in the
#incompleteMessage div, which contains the "Please complete all the fields..."
message. We keep the message there for the time specified by the messageDelay
variable, then fade it out again. Once it's faded out, we fade the form back in so that
the user can complete it.
4. Submit the form if it is completed
Now we get to the meat of the JavaScript. If the form is completed then we first fade
out the form, and fade in the "Sending your message..." box. Now we call the jQuery
ajax() method to submit the form via Ajax to the PHP script. We pass the following
arguments to the method:
5. Prevent the default form submission occurring
Finally, our event handler returns false to prevent the form being submitted in the
usual way.
6 WH S : ULWH WK H submitFinished() I X Q F WLR Q
The last function we need to write is submitFinished(), which is called once the Ajax
11/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
response from the PHP script has been received by the browser. This function needs to
check the response and display a success or error message as appropriate:
The function works as follows:
1. Get the response
jQuery passes the response from the PHP script as an argument to the
submitFinished() function. We take this string and pass it through the jQuery
trim() method to remove any whitespace.
2. Fade out the "sending" message
Next we fade out the "Sending your message..." box by calling the jQuery fadeOut()
method.
3. If email was sent successfully, display a success message
If the response variable holds the string "success", as returned by our PHP script,
then we know that the email was successfully queued for delivery. So we fade in the
success message, hold it for a couple of seconds, then fade it out. We also reset the
form fields to empty values, in case the user wants to send another message. Finally,
once the success message has faded out, we fade the page content back in.
4. If there was a problem, display a failure message
If the PHP script returned anything other than "success" then we know there was a
problem with the submission, so we display the failure message stored in the
#failureMessage div, then fade the form back in so that the user can correct any
problems with the form.
And that's the end of our JavaScript!
6 X P P D U\
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Handle the Ajax response

function submitFinished( response ) {
response = $.trim( response );
$('#sendingMessage').fadeOut();

if ( response == "success" ) {

// Form submitted successfully:
// 1. Display the success message
// 2. Clear the form fields
// 3. Fade the content back in

$('#successMessage').fadeIn().delay(messageDelay).fadeOut();
$('#senderName').val( "" );
$('#senderEmail').val( "" );
$('#message').val( "" );

$('#content').delay(messageDelay+500).fadeTo( 'slow', 1 );

} else {

// Form submission failed: Display the failure message,
// then redisplay the form
$('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
$('#contactForm').delay(messageDelay+500).fadeIn();
}
}

</script>
12/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
View Demo
Buy from
Amazon.com
Buy from
Amazon.co.uk
Link HTML:
Tweet Tweet
83


6 K D UH 7 K LV 3 D J H
Link to this page

) R OOR Z ( OD WH G
Subscribe to the Elated
Newsletter
We've now built our slick Ajax contact form. Not only does it look good, but it's easy to
use, and the visitor can send an email without ever having to leave the page they are
reading. Nice!
Here's the demo again:
I hope you enjoyed following this tutorial. Feel free to use the code in your own
projects if you like. As always, if you have any comments, suggestions or questions on
the tutorial, please do post them in the responses below.
Have fun!
/ HDUQ 3 + 3 : LWK ( DVH
Written by Matt Doyle ELATED's resident Web
programming expert Beginning PHP 5.3 is a complete
introduction to PHP, covering everything in these tutorials
and lots more besides. Find out how to:
Set up PHP on your computer
Use strings, arrays, functions and objects
Create interactive Web forms
Handle cookies and sessions
Work with files on the server
Build database-driven sites with MySQL
Send emails from your scripts
Create images on the fly with PHP
Work with regular expressions
Write robust, secure PHP applications
...and lots more!
What a pleasure it's been spending hours and hours
studying PHP with this magical book. Lul i o, Fl ori da
The book is not only great for learning, but I find myself
using it constantly as a reference as well! Davi d A.
Stol tz
Buy Beginning PHP 5.3 now from Amazon.com or Amazon.co.uk.
13/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
<a href="http://www.elated.com/articles/slick-ajax-contact-form-jquery-php/">How to Make a Slick Ajax Contact Form with jQuery and PHP</a>
URL only:
http://www.elated.com/articles/slick-ajax-contact-form-jquery-php/
Your Email Address...
Get tips, tricks and site updates once a month!
Free web template when you sign up! Privacy
Send Send
5 H OD WH G D UWLF OH V
How to Add Image Uploading to Your
CMS
How to Add Article Categories to
Your CMS
JSON Basics: What You Need to Know
Build a CMS in an Afternoon with PHP
and MySQL
PHP References: How They Work,
and When to Use Them
How We Redesigned Elated.com: The
Build Process
Create Nice-Looking PDFs with PHP
and FPDF
PHP For Loops
PHP While Loops
jQuery Mobile 1.1: Smoother, Faster, Nicer
Ajax with jQuery: A Beginner's Guide
jQuery Mobile Masterclass: Build a Simple, Attractive Twitter App for iPhone
Cover Flow Remade with CSS and jQuery
How to Make an Elegant Sliding Image Gallery with jQuery
Drag-and-Drop with jQuery: Your Essential Guide
jQuery Mobile: What Can It Do for You?
Create Smooth Rotatable Images with CSS3 and jQuery
A Snazzy Animated Pie Chart with HTML5 and jQuery
5 H VS R Q VH V WR WK LV D UWLF OH
20 most recent responses (oldest first):
amin 15-Apr-12 14:35
ok so u say that for using unicode characters we have to use a "u" flag.
Can you please explain exactly how should we write the preg_replace function here
with the "u" flag and the whitelist that you mentiond? cause I cant make it work!!
thanks!
aliveit 16-Apr-12 08:47
Hi Matt, I added this form to a site last year and it worked great and looks great. The
problem is the form has stopped working. There has been some content added over
the last few months so its possible something has been changed but I can't find it.
The form is at www.listertrack.co.uk, when you click to submit you are left with a
message that says "Sending your message, please wait". The email is not coming
through and that message stays on the screen until you refresh.
Could I please ask that you point me in the right direction to solve this problem.
14/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
Many thanks
Dave
matt 27-Apr-12 18:44
@amin: I don't know the Persian character set or how it works with regular
expressions in PHP, so I'm not sure exactly what you'd put in the whitelist. But
essentially you want to add the range of all allowable Persian characters (the Persian
equivalent of A-Za-z0-9).
matt 27-Apr-12 18:48
@aliveit: Try turning off JavaScript in your browser then reload the page and submit
the form. See what happens.
vassilij 27-Apr-12 20:42
Hi Matt, I used this excellent tutorial for my website but I have several problems with
Internet Explorer. The first is that not any text appears on the labels of the
placeholder. The second problem is that when I send an email even if it is poorly
written and without the "@", continues to send the email.
This is the link to my website: www.kromweb.com
I do not know that I have to do to fix it. I would appreciate your help.
thank you very much
matt 10-May-12 04:47
@vassilij: IE <=9 doesn't support HTML5 placeholders. I believe support is coming in
IE10. I covered email address validation earlier in the topic:
http://www.elated.com/forums/topic/5171/#post22571
vassilij 10-May-12 16:30
Hi Matt, thanks for answering.
I'm not a programmer and do not know javascript or php.
I looked at the comment that you say but I can not make it work.
I've been looking online and found a plugin to validate html5 forms but does nothing.
Is as follows: http://www.matiasmancini.com.ar/jquery-plugin-ajax-form-validation-
html5.html
I do not know as I have to do to make the form work well in Internet Explorer, I'm
going crazy .. lol
I send my code to see if you can help me.
15/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
<!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=utf-8" />
<title>Kromweb</title>
<link rel="stylesheet" type="text/css" href="estilos/estilos.css"/>
<link href="img/favicon_kromweb.png" rel="shortcut icon"/>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="estilos_IE.css" />
<![endif]-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var messageDelay = 2000; // How long to display status messages (in milliseconds)
// Init the form once the document is ready
$( init );
// Initialize the form
function init() {
// Hide the form initially.
// Make submitForm() the form's submit handler.
// Position the form so it sits in the centre of the browser window.
$('#contactForm').hide().submit( submitForm ).addClass( 'positioned' );
// When the "Send us an email" link is clicked:
// 1. Fade the content out
// 2. Display the form
// 3. Move focus to the first field
// 4. Prevent the link being followed
$('a[href="#contactForm"]').click( function() {
$('#lista').fadeTo( 'slow', .2 );
$('#contactForm').fadeIn( 'slow', function() {
$('#senderName').focus();
} )
return false;
} );

// When the "Cancel" button is clicked, close the form
$('#cancel').click( function() {
$('#contactForm').fadeOut();
$('#lista').fadeTo( 'slow', 1 );
} );
// When the "Escape" key is pressed, close the form
$('#contactForm').keydown( function( event ) {
if ( event.which == 27 ) {
$('#contactForm').fadeOut();
$('#lista').fadeTo( 'slow', 1 );
}
} );
}
// Submit the form via Ajax
function submitForm() {
var contactForm = $(this);
// Are all the fields filled in?
if ( !$('#senderName').val() || !$('#senderEmail').val() || !$('#message').val() ) {
// No; display a warning message and return to the form
<?php
// Define some constants
define( "RECIPIENT_NAME", "Name" );
define( "RECIPIENT_EMAIL", "kromweb@kromweb.com" );
define( "EMAIL_SUBJECT", "Asunto del Mensaje" );
// Read the form values
$success = false;
$senderName = isset( $_POST['senderName'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/",
"", $_POST['senderName'] ) : "";
$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-
9]/", "", $_POST['senderEmail'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace(
"/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";
// If all values exist, send the email
if ( $senderName && $senderEmail && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}
// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
} else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<?php if ( $success ) echo "<p>Gracias por enviar su mensaje. Le responderemos lo
antes posible.</p>" ?>
<?php if ( !$success ) echo "<p>Ha habido un problema al enviar su mensaje. Por
favor, intntelo de nuevo.</p>" ?>
<p>Pulse atrs en el navegador para volver a la pgina anterior.</p>
</body>
</html>
<?php
}
16/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
?>
Thank you very much.
[Edited by vassilij on 20-May-12 16:54]
cjdesigns 23-Jun-12 23:25
Matt,
Thanks for this tutorial! It really is great. I have one problem with the form.
The message sends successfully but the contact form doesn't reappear after sending
and doesn't come back if the cancel button is pressed.
I've looked over the code and it looks like all the fade ins and outs are correct. I can't
figure out why the form doesn't come back.
Here is a link to my website : http://charlesjulianj.aisites.com/imd311/index3.html
UPDATE: I figured it out. I'm not sure if it was the best way to bring the contact form
back but I added fade in to the following code
$('#contactForm').delay(messageDelay+500).fadeTo( 'slow', 1 ).fadeIn();
[Edited by cjdesigns on 24-Jun-12 15:32]
enodia 29-Jun-12 03:07
Where shall i change the email address to send the emails to?
Thank you!
*Edit: Found out! Sorry for the silly question!
[Edited by enodia on 29-Jun-12 04:13]
neutronium 07-Jul-12 12:08
why i always get fail to send the message
i only change the
define( "RECIPIENT_NAME", "xxxx" );
define( "RECIPIENT_EMAIL", "xxxx@gmail.com" );
define( "EMAIL_SUBJECT", "xxxx" );
17/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
is there other value I need to change?
I always getting fail with the php contact system
steffo91 10-Jul-12 03:27
Hey guys,
I need your help for a project I am working on, I believe it's nothing to hard, but I am a
newbie with PHP and don't know how to solve it on my own.
So, I have followed the tutorial and now I have my form working, but if I try to put
Chinese characters in the Name field (so in php is in the header), it becomes
impossible to submit the form...
I have looked online, but I haven't been able to understand how to encode stuff in to
charset utf8 or something.
Your help would be greatly, hugely, immensely appreciated.
Thanks, and again thanks for such a wonderful tutorial.
Ste
matt 13-Jul-12 02:50
@neutronium: What sort of fail? What error message are you seeing exactly?
@steffo91: What do you mean by "impossible to submit the form"? You'll probably
need to modify the appropriate regex in the PHP to allow for Chinese characters.
neutronium 13-Jul-12 03:42
not the problem with your php.
actually, i can't send mail though php...
i using appserv and start server with my home computer
i want to use gmail as smtp, but it was confusing
matt 16-Jul-12 02:01
@neutronium: Sending gmail using SMTP auth:
http://stackoverflow.com/questions/10380051/how-do-i-send-email-using-gmail-
through-mail-where-do-i-put-the-password
mcall 06-Aug-12 16:01
If i put checkboxes into the the form, how would I set up the php to pull the info of
which ones get checked?
thanks
matt 10-Aug-12 02:11
@mcall: See http://www.html-form-guide.com/php-form/php-form-checkbox.html
truitas 10-Aug-12 02:40
18/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
hi matt and everybody,
some month ago i used your form and i forgot to show you the result.
if it can help somebody it's here:
http://savoie-rando.fr/contact.html
thanks
yan
ambersdad1 21-Aug-12 22:26
Of all the forms that I have seen, this example is the best...hands down! I love the way
it works. However, here is my question:
When you cancel the form and you have entered data, there is a line of code that
clears the text fields. Here it an example:
$('#someField').val("");
That works great for a text input field. However, the form that I am working on has a
select statement. For example:
<li>
<label for="typeOfPet">Favorite type of pet:</label>
<select name="typeOfPet">
<option value="">Select...</option>
<option value="D">Dog</option>
<option value="C">Cat</option>
<option value="B">Bird</option>
<option value="R">Reptile</option>
<option value="O">Other</option>
</select>
</li>
When I cancel the form, how do I reset the value for the input field? I tried:
$('#typeOfPet').val(0);
to select the first option value. I have learn an incredible amount of coding with this
example for which I am very grateful for but I am stuck on how to reset the value
because after I cancel the form and then reopen the form, I still see the selected value
that was chosen before I hit cancel.
ambersdad1 22-Aug-12 08:01
After MANY hours of searching, I stumbled upon how to clear the fields. The method
that seems to work is as follows:
$('#petForm').get(0).reset();
Where #petForm is the name of the form and get(0) is the very first field within the
form.
Stanley 24-Aug-12 17:06
Nice form Matt. I've just ironed out a few problems I experienced while trying to work
it into my existing site and thought I'd share a few things I had trouble with, and how I
solved them. A lot of trying to run before I can walk here!
First it was difficult to get the thing to size properly so I had to tweak a few things in
19/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
my existing CSS to get the form to display at the right scale.
Secondly while developing on my own machine (localhost) I was having a problem
with the name and email boxes appearing as different widths - but only in Opera. It
turned out (after much head scratching) that the php warning I was living with while
working on my local machine (it was a SimplePie warning that the cache folder wasn't
writable) was somehow throwing the form fields out in Opera. They worked great in
other browsers but it was only when I decided to get rid of the warning message at the
top of the page that Opera decided to play ball.
Thirdly (Opera again) I had a problem with the italicised characters getting "chopped
off" in the form header. This is something to do with Opera not liking fonts being
italicised when there isn't an italic version in the font itself (or something like that).
Again I was trying to get it to work with the font I was already using on the page
(Tahoma) which worked in every other browser than Opera. Changing the font-family
back to what you have in the demo cured the problem.
Last but not least I also experienced the problem noted by @aliveit where the error
message stayed on the screen instead of fading out and returning to the form. Apart
from not actually having a #content div on my existing page (I had one called wrapper
which I eventually renamed to content) it turned out that the real culprit in my case
was simply that I was already using jQuery for something on the page, and I was trying
to use that instead of the one which you have in the source code. When I switched to
using that everything worked
Hope this helps someone.
P.S. Matt,
I want to use the same type of form for my site sign up and also for someone to send
me an actually enquiry, rather than a general message. How would you go about
implementing that? Would it work if I wrote three separate sets of forms and handling
scripts?
I've already had to rename the function from init() to initform() to avoid a conflict with
your javascript tabs script, so I suppose it should be possible to triplicate everything?
Or can you suggest a cleverer way for me to investigate? I was thinking along the lines
of having a second set of js tabs which pop up like this contact form, but with a
different form on each tab.
Ideally I'd like the enquiry form to allow someone to attach a file too, but I'll cross that
bridge when I come to it.
[Edited by Stanley on 24-Aug-12 23:17]
View all 214 responses
Post a response
Want to add a comment, or ask a question about this article? Post a response.
To post responses you need to be a member. Not a member yet? Signing up is free,
easy and only takes a minute. Sign up now.
Top of Page
20/20 www.elated.com/articles/slick-ajax-contact-form-jquery-php/
Home
About Elated
Advertise
Contact Us
FAQ
Spamwars
Link to Us
RSS
Twitter
Facebook
Articles
PageKits
ImageKits
ActionKits
Forums
Newsletter
This site Elated Communications 1996-2012.
Unauthorised copying or redistribution prohibited.
By using this Website, you are indicating your
acceptance of our Terms of Use.
Please read our Privacy Policy.

Vous aimerez peut-être aussi