How to Make a Slick Ajax Contact Form with jQuery and PHP

  You are currently not logged in. You can view the forums, but cannot post messages. Log In | Register

01-Apr-11 00:00
This is a forum topic for discussing the article "How to Make a Slick Ajax Contact Form with jQuery and PHP":

http://www.elated.com/articles/slick-ajax-contact-form-jquery-php/

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.
08-Apr-11 01:29
I can't believe nobody has commented yet! This tutorial is amazing and so helpful! Thank you!

--
www.DestinationMoonDesigns.com
08-Apr-11 01:49
@DestMoonDesigns: Yay, thanks for your feedback - glad you liked it!

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
20-Apr-11 10:29
Yes, this is amazing and well done. Bravo and thank you.

I'm trying to use it for a registration form. It's very nice.
I wonder what is the syntax for adding to the submitForm function a regex validation.
Let's say the regex below.


/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/


All my best.
23-Apr-11 12:25
Slick tool. I like it!

I have a question though...

I would like to place the css and javascript code that are now in the index.html file, in separate files, which I can include with tags like so:

<link rel="stylesheet" type="text/css" href="/ajax-contact-form/ajax-contact-form.css">

<script type="text/javascript" src="/ajax-contact-form/ajax-contact-form.js">

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

Is this possible?
25-Apr-11 02:31
@hcharles: Thanks!

How about something like:


if ( !$('#fieldName').val().match( /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/ ) ) {
// invalid
}



?

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
25-Apr-11 02:43
Thank you Matt.
Yes it's exactly what I needed.

Great site, great job.
25-Apr-11 04:46
@mktngguy: Yep, totally possible. Although you should put the jQuery include before the others.

@hcharles: Great stuff!

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
28-Apr-11 16:16
wow matt, THIS is exactly what i have been looking for in a long time!

This is one of the most comprehensive tutorials i have read in a long long time! So much effort in it... i can tell you love what you do and i do respect that a lot!

I just registered to tell you that

Greetings from Germany!
29-Apr-11 06:21
@phrill: Thank you so much for your kind words - that's really great to hear!

Cheers,
Matt

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
29-Apr-11 18:17
this is excellent, thanks for making it available..

i have a small problem, the form comes up on the site, i can fill in details, and send, but...

it says...sending message....

but then says...there was a problem, try again....

but i'm receiving the sent message in my inbox, so as far as i can tell there was no problem sending ?
02-May-11 02:05
@naval1: That's strange. Your PHP script might be exiting abnormally for some reason - that would stop it returning the correct response to the JavaScript. You'll need to do some debugging I think. You could try disabling JavaScript in your browser, and adding ?ajax=true to your form action:

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

This should make the PHP script think it's handling an Ajax request. You can then see the response from the PHP script in the page.

You could also try using PHP's error_log() function and the error_log directive to log diagnostic messages to a log file on your server. This might help you work out what's happening inside the PHP script.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
02-May-11 14:07
Thanks Matt,

I'm very new to web site design and its taken me months to design my own site with no previous html, java script or php experience.

I've followed your instructions to the letter, and saw the response from the php script and found that the problem was with script recommended by my site hosts, details as follows:

To prevent spam being sent through our webservers, there are certain conditions that must be met before our SMTP servers will send the email.

Email must be sent to, or from, an existing email address hosted by Fasthosts. This must be a mailbox on the same domain name on which the form to mail script is being hosted.
To stop misuse of your form by third parties the sendmail_from variable should be set to your Fasthosts hosted email address. While access to the php.ini file is restricted on our shared environment, you can sent this variable using the ini_set() command, shown below.
A fifth parameter, -f, should be added to the sendmail function. This will set the name of the from email address.
In its basic form, a simple sendmail script will look like this:

<?php
ini_set("sendmail_from", "user@yourdomain.com");
mail($email_to, $email_subject, $email_message, $headers, "-fuser@yourdomain.com");
?>
Provided that your form to mail script meets the requirements above, you should have no problems.

I've removed their recommended php script and everything works fine now. Is there anything I need to do or do I just leave things as they are ?

Again thank you very much for your time, what a very informative site you run, thank you.
05-May-11 05:50
@naval1: Not sure how your mail was getting sent in that case, but anyway...

If it ain't broke, don't fix it, is my motto!

Matt

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
05-May-11 12:36
Hello Matt,

Based on your wonderful tutorial, I've created a registration Form.
After the form is submitted, I'm using a php script to create an image (imagecreatefrompng).

Emailing the created image to the registered user is working fine.

Now I'm trying to send the img to the browser.
The header is set in my php code

header( "Content-type: image/png" );


My question is how to reprocess the return by Ajax in order to display the image for download purpose.
I read lot today about this question; until I get lost.
In advance Thanks.
-Charles
07-May-11 10:41
Just had to say this is TOTALLY AWESOME!!! I incorporated it into the new wordpress theme I am designing for my site and it works great.

Can't thank you enough. Keep up the good work.
08-May-11 02:44
Hello Matt,

In my previous post I was asking you: "how to reprocess the return by Ajax in order to display an image for download purpose".

The idea is to use AJAX to modify the content which was displayed from the index.html before the form is submitted; as part of the form's submission result.

I managed to do so.
To share with others, here's how:

In File "index.html", I added a new div.
That's the div I'm going to modify through the AJAX Response.


<div id="info">This text will be replaced after form submission.</div>


In processFrom.php, I modified the response to the browser. I just added my info (file url) to the success variable.

The original code from elated.com to modify is

if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";


After my modifications it looks like this

if ( isset($_GET["ajax"]) ) {
echo $success ? "success|$file_link" : "error";

The var file_link was created by some earlier php codes in the processFrom.php file. It contains an img tag or a "File not created error message".

The last thing to do was to modify the response processing code in index.html.
The original code from elated.com to modify is within the submitFinished function


response = $.trim( response );


Changes are like this

var result = response.split("|");
var success_resp = $.trim( result[0] );
var new_info = $.trim( result[1] );


Just after this code I changed the original

if ( response == "success" ) {


to

if ( success_resp == "success" ) {


and just before the original code

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


I added my new info (img tag) to the div I've created at the beginning

$('#info').replaceWith(new_info);


I started learning AJAX a few days ago thanks to this tutorial from Matt.
Thanks Matt.

[Edited by hcharles on 08-May-11 02:49]
09-May-11 05:27
Awesome tutorial!!
I am using all this information for a website that I am building, but there is one problem that I can't solve...

When I submit the form it always return an error:

"There was a problem sending your message. Please try again." (The message from failureMessage)

I have checked the code several times but found no errors... I'm at a loss...

Can someone help me?

Here is the code for the form:

<article id="contact">
<form action="process_form.php" method="post" id="contact_form">
<h2>お問合せ</h2>
<div id="cancel">閉じる</div>
<fieldset>
<label for="name">お名前</label>
<label for="name" class="error" generated="true"></label>
<input type="text" name="name" class="form_input required" id="name" size="50" />
<label for="phone">電話番号</label>
<label for="phone" class="error" generated="true"></label>
<input type="text" name="phone" class="form_input required" id="phone" size="50" />
<label for="email">メールアドレス</label>
<label for="email" class="error" generated="true"></label>
<input type="text" name="email" class="form_input required email" id="email" size="50" />
</fieldset>
<fieldset>
<label for="message">ご要望</label>
<label for="message" class="error" generated="true"></label>
<textarea name="message" rows="5" class="required" id="message"></textarea>
</fieldset>
<fieldset>
<input type="submit" name="submit" value="送信" class="contact_button" />
</fieldset>
</form>
<div id="sending-message" class="status-message">
<p>お問合せの内容は貴方宛に送信しています。しばらくお待ち下さい。</p>
</div>
<div id="success-message" class="status-message">
<p><strong>ありがとうございました!</strong> お問合せの内容は貴方宛に送信致しました。後ほど改めて詳細をメール致します。</p>
</div>
<div id="failure-message" class="status-message">
<p><strong>エラーがありました!</strong> もい一度内容を入力して下さい。</p>
</div>
<div id="incomplete-message" class="status-message">
<p>全てのフィールドは必須です。</p>
</div>
</article>


Here is the code for the JavaScript:

<script>
var messageDelay = 2000;
$( init );
function init() {
$('#contact_form').hide().submit( submitForm ).addClass( 'positioned' );
$('a[href="#contact_form"]').click( function() {
$('#page-wrapper').fadeTo( 'slow', .2 );
$('#contact_form').fadeIn( 'slow', function() {
$('#name').focus();
} )
return false;
} );
$('#cancel').click( function() {
$('#contact_form').fadeOut();
$('#page-wrapper').fadeTo( 'slow', 1 );
} );
$('#contact_form').keydown( function( event ) {
if ( event.which == 27 ) {
$('#contact_form').fadeOut();
$('#page-wrapper').fadeTo( 'slow', 1 );
}
} );
}
function submitForm() {
var contact_form = $(this);
if ( !$('#name').val() || !$('#phone').val() || !$('#email').val() || !$('#message').val() ) {
$('#incomplete-message').fadeIn().delay(messageDelay).fadeOut();
contact_form.fadeOut().delay(messageDelay).fadeIn();
}
else {
$('#sending-message').fadeIn();
contact_form.fadeOut();
$.ajax( {
url: contact_form.attr( 'action' ) + "?ajax=true",
type: contact_form.attr( 'method' ),
data: contact_form.serialize(),
success: submitFinished
} );
}
return false;
}
function submitFinished( response ) {
response = $.trim( response );
$('#sending-message').fadeOut();
if ( response == "success" ) {
$('#success-message').fadeIn().delay(messageDelay).fadeOut();
$('#name').val( "" );
$('#phone').val( "" );
$('#email').val( "" );
$('#message').val( "" );
$('#page-wrapper').delay(messageDelay+500).fadeTo( 'slow', 1 );
}
else {
$('#failure-message').fadeIn().delay(messageDelay).fadeOut();
$('#contact_form').delay(messageDelay+500).fadeIn();
}
}
</script>


Here is the code for the php mailer:

<?php

// Define some constants
define( "RECIPIENT_NAME", "JPB泉南" );
define( "RECIPIENT_EMAIL", "ruiz@junctionproduce-boutique.jp" );
define( "EMAIL_SUBJECT", "お問合せ" );

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

// If all values exist, send the email
if ( $name && $phone && $email && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $name . " <" . $email . ">";
$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>お問合せ</title>
</head>
<body>
<?php if ( $success ) echo "<p><strong>ありがとうございました!</strong> お問合せの内容は貴方宛に送信致しました。後ほど改めて詳細をメール致します。</p>" ?>
<?php if ( !$success ) echo "<p><strong>エラーがありました!</strong> もい一度内容を入力して下さい。</p>" ?>
<p>ブラウザーの「戻る」ボタンを押して下さい。</p>
</body>
</html>
<?php
}
?>


Thank you in advance!

[Edited by maruse on 09-May-11 05:32]
09-May-11 08:14
@Maruse,
Hello.

I had the same problem with php mail function.
It was in relation with the recipient's DNS configuration.
MX records is not configured.

Try to use the PEAR::Mail function. It's more robust.
Working for me.

Good luck.
-Charles
09-May-11 21:53
@hcharles

Thank you for your response but, please excuse my ignorance but I'm new to PHP and my knowledge is very limited.

Can you show me how to implement that function in my code?

Thank you.
10-May-11 01:41
@Maruse,

Pear is a PHP Extension.
You need to check if it is installed on your server.
Follow this doc:

http://pear.php.net/manual/en/installation.checking.php


There are a lot of "Pear - howto" in the net.
You may give a look at this one for some samples of Text or html email, with one or more attachments:

http://www.phpmaniac.net/wiki/index.php/Pear_Mail

Hope this helps.
-Charles
10-May-11 02:13
@tsquez: Great stuff, thanks for your kind words

@hcharles: Yep, your image mod is pretty much how I'd have done it too!

@maruse: You might also want to turn on PHP error logging - that might tell you exactly what the problem is with the script:

http://www.php.net/manual/en/errorfunc.configuration.php#ini.log-errors

http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-log

It's likely that your PHP mail config needs tweaking. See @naval1's post earlier in the thread re sendmail_from etc.

Matt

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
10-May-11 04:22
Thank you all for your help, but it seems I can't get it to work...
10-May-11 22:27
I found what is the error.

If I fill the contact form using English, then everything is fine but if I fill the form in Japanese, then it breaks and I get the error message.

The encoding of my page is UTF-8 so I don't understand why I get that error.

Any ideas?

Edited:

I found the problem. It wasn't the encoding but one of the functions in the php file.

I replaced preg_replace with strip_tags and now everything is working fine even in Japanese.

[Edited by maruse on 10-May-11 23:16]
12-May-11 05:14
@maruse: Glad you got it working! Re preg_replace(), try using the 'u' flag:

http://th1rty7.blogspot.com/2008/12/unicode-and-pregreplace.html

strip_tags() is OK but it's better to use preg_replace() with a whitelist if possible.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
16-May-11 16:29
Hi Matt,
Thank you for this great tutorial. It's looking beautiful but unfortunately I can't get it to work properly. After I fill in all the fields and submit the form I get the "incompleteMessage" error message. I imagine there's a problem with the validation process but as I'm new the php I can be sure. Any way you can take a look for me?

I kept things pretty simple as you had in your demo, here's my html:


<form id="contactForm" name="contact" action="processForm.php" method="post">
<div class="contact-name">
<label id="senderName_label">Your Name</label>
<input type="text" name="senderName" id="senderName" placeholder="Please type your name" required="required" maxlength="30" />
</div>

<div class="contact-email">
<label id="senderEmail_label">Your Email</label>
<input type="email" name="senderEmail" id="senderEmail" placeholder="Please type your email address" required="required" maxlength="30" />
</div>

<div class="contact-message">
<label id="senderMessage_label">Your Message</label>
<textarea name="message" id="message" placeholder="Please type your message" required="required" cols="80" rows="10" maxlength="10000"></textarea>
</div>
<input type="submit" id="sendMessage" name="sendMessage" value="Send Email" />
</form>



Here's the php:


<?php

// Define some constants
define( "RECIPIENT_NAME", "Denise Rotman" );
define( "RECIPIENT_EMAIL", "hello@deniserotman.com" );
define( "EMAIL_SUBJECT", "deniserotman.com Vistor" );

// 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>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>


And here's the javascript, I wanted to remove the hide functionality you had for the demo which is why some of the code has been commented out. I want the form to be there once you arrive at the section and only hide once you submit the form.



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').show().submit( submitForm );

// 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() {
$('#contactForm').fadeOut();
$('#content').fadeTo( 'slow', 1 );
} );

// When the "Escape" key is pressed, close the form
$('#contactForm').keydown( function( event ) {
if ( event.which == 27 ) {
$('#contactForm').fadeOut();
$('#content').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
$('#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
return false;
}


// 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();
}
}



Thank you! I will thoroughly appreciate your (additional) help!
Denise

--
Drot
19-May-11 04:15
@drot: Please post the URL of your complete page in a new topic so we can see the exact problem in action:

http://www.elated.com/forums/authoring-and-programming/topic/new/

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
29-May-11 17:36
you are awesome! thank you!
30-May-11 22:33
@ninka: You're welcome

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
11-Jun-11 22:11
Thanks Matt for the awesome tutorial...

I have a question : I want to add more fields to the form. When I tried adding, some fields and the buttons below were no longer visible in the form.

How do I add a scroll bar to the form in case there are more fields for input? Please help.
20-Jun-11 05:31
@aditi_sharma: You could try:


#contactForm { overflow: scroll; }


Does that help?

Cheers,
Matt

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
27-Jun-11 13:12
How can I change the form to a registration form? I tried to change the processform.php to insert the information but I guess that's not the way, can anyone help? thanks!!
27-Jun-11 23:27
@topsyk: That certainly is the way! If you're having specific problems then please post your PHP script in a separate topic and we can take a look:

http://www.elated.com/forums/authoring-and-programming/topic/new/

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
28-Jun-11 11:51
Hi,

Nice Contact Form Sample. I make an alternative for those are using servers like yahoo server.


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


with yahoo server or any other similar the email has to be send it from inside or it won't go trough.

enjoy

mbarcala
28-Jun-11 12:22
Hi Matt,

This is the exact functioning form I have been looking for. Looks great and works great! Except for one little thing...sorry.

I fill out the form and click submit. I get the "Sending your message" message. Then the "thanks for sending your message" message. But then the message just stays there. I've tried adjusting the
var messageDelay = 2000; line of code to a lower number, but not avail.
I should mention that the email does go through, with all headers, email addresses and text in place.
My page is here: http://www.ericmlyons.com/index_contact.html.

And here is the code I'm using:

the javascript (please note that I replaced #content with #linkwrapper as this is where my content is)


<script type="text/javascript">

var messageDelay = 500; // 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() {
$('#linkwrapper').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();
$('#linkwrapper').fadeTo( 'slow', 1 );
} );

// When the "Escape" key is pressed, close the form
$('#contactForm').keydown( function( event ) {
if ( event.which == 27 ) {
$('#contactForm').fadeOut();
$('#linkwrapper').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
$('#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
return false;
}


// 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( "" );

$('#linkwrapper').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>


and

My php code:

<?php

// Define some constants
define( "RECIPIENT_NAME", "Eric Lyons" );
define( "RECIPIENT_EMAIL", "mail@ericmlyons.com" );

// 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'] ) : "";
$senderSubject = isset( $_POST['senderSubject'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderSubject'] ) : "";
$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 && $senderSubject && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail( $recipient, $senderSubject, $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>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>


I would really appreciate the help. It's working exactly how i need it to work, except for that glaring issue. You rock! Thank you so much.

Eric
29-Jun-11 11:07
Love this tutorial, but I am new to all of this. I want to add a field for a phone number and a drop down selection box to choose your product, but it won't post.

Also now, (for some reason) When I try the form out I get the success message, but no email comes. What am I doing wrong?



<?php

// Define some constants
define( "RECIPIENT_NAME", "Action Graphics Sales" );
define( "RECIPIENT_EMAIL", "10000nails@gmail.com" );
define( "EMAIL_SUBJECT", "Quote Request" );

// 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'] ) : "";
$senderPhone = isset( $_POST['senderPhone'] ) ? preg_replace( "/[^\.\' a-zA-Z0-9]/", "", $_POST['senderName'] ) : "";
$Product = isset( $_POST['cf_drop_down'] );
$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 && $senderPhone && $Product && $message) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail( EMAIL_SUBJECT, $recipient, $senderPhone, $Product, $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>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>
01-Jul-11 01:08
@edub187: You're using a very old version of jQuery (1.3.2). Try the latest version (1.6.2): http://jquery.com/

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
01-Jul-11 01:10
@10000nails: Please post the URL of your form in a new topic so we can take a look at it in action:

http://www.elated.com/forums/authoring-and-programming/topic/new/

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
01-Jul-11 07:18
Matt,

Thank you SO much. I updated my jquery link and it works flawlessly. Great tutorial. Great outcome. And great assistance. Thanks again.

Eric
01-Jul-11 07:54
Hi Matt,

I would like to know how could I pass an info to the subject or textarea part in the form from a button or a regular link using innerhtml action.

let say that I have a button that say "click me" and i want when click the button i pass the "picture number or name" inside the subject or the Textarea part.

I try to follow many samples from the internet but any of those samples let me place the value or the text i want inside the input field in the form? so can you give me a hand on this please?

thanks

mbarcala
04-Jul-11 23:10
@edub187: Great stuff

@mbarcala: If I understand it correctly, your question is not really related to the article - it's more a general JavaScript forms question. Please post it in a new topic:

http://www.elated.com/forums/authoring-and-programming/topic/new/

Cheers,
Matt

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
05-Jul-11 12:55
I was wondering if there was a way to CC a couple of email addresses? Great script by the way. works like a charm.

Kate

--
Kate FIshwick
05-Jul-11 13:39
I just set the forward in the mail client. =)

--
Kate FIshwick
05-Jul-11 23:07
@redfraggle42: Yep:


$headers = "From: " . $senderName . " <" . $senderEmail . ">\r\n";
$headers .= "CC: " . $ccName . " <" . $ccEmail . ">\r\n";


--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
13-Jul-11 09:10
This is a wonderful contact form. It is exactly what I wanted...
I just have one question: When the contact form is visible, there's kind of a white layer beneath the form and over part of the page (like a veil).
Is it possible to extend this "veil" to the entire page?

I'm not sure if I'm explaining myself well....
13-Jul-11 09:58
@perfisa
I believe in order to veil the entire page, you need to select which div you want in the fade to portion of the javascript init function. For example:


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() {
$('#[b]linkwrapper[/b]').fadeTo( 'slow', .2 );
$('#contactForm').fadeIn( 'slow', function() {
$('#senderName').focus();
} )


where linkwrapper is the area of the page you wish to white out. That's how I did it on my page, and it seems to work. Please correct me if I'm wrong.
14-Jul-11 04:14
@ edub187

Thank you very much. It worked perfectly.
21-Jul-11 05:38
Bravo.
Toutes mes félicitations.
After a little issue I finally made it.

Tous mes remerciements.
(that means, warm thanks).
22-Jul-11 00:18
@Sventovit: Pas de problème. Je suis content qu'il est fixé maintenant!

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
22-Jul-11 01:20
Ah ah!
Beware... As you improve my coding skills, I’m might improve your french. ;-p

Matt, may I suggest one thing?
Thank you.
You should add the Google Plus 1 button (http://www.google.com/+1/button/) to your pages.
Your articles worth it.
26-Jul-11 02:18
@Sventovit: Ha ha, yes my French is not very good these days

Thanks for the +1 suggestion - we'll look into it.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
02-Aug-11 14:19
Hi Matt,

I have another question in reference to this email form, i would like to know how I can format the email body that I will receive from the web in the php file? I mean how i can put it like this

name
phone

message here

I don't know if this have to be a new post?

I add a new field for a phone information but it came under the message part? this is for my own eyes purpose only but i really would like to know if this can be done in some point in this way

Regards

mabrcala
04-Aug-11 11:26
i need to define the from address and have the senders email address be set as a reply to address. it seems to be required by godaddy that the from address be from the same domain as the website itself otherwise no email is sent. i have tried and tried to get it to work but no matter what i do to try and fix still it gives me the you must fill in all boxes message when i hit send. in the html file i renamed the box for email address "replyEmail" and set a define in the top of php for the from... here's my php i am fairly sure the problem is here:




<?php

// Define some constants
define( "RECIPIENT_NAME", "Axiom Build + Print" );
define( "RECIPIENT_EMAIL", "info@theaxnyc.com" );
define( "EMAIL_SUBJECT", "Website email/ quote request" );
define( "SENDER_EMAIL", "info@theaxnyc.com" );

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

// If all values exist, send the email
if ( $senderName && $replyEmail && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$senderEmail = " <" . SENDER_EMAIL . ">";
$headers = "From: " . $senderEmail . "\r\n";
$headers .= "Return-Path: " . $senderName ." <" . $replyEmail . ">\r\n";
$headers .= "Reply-to: " . $senderName . " <" . $replyEmail . ">";
$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>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>


also here is the link to my test page (just the original demo page until i get contact form working) :
http://theaxnyc.com/newformfile.html

thanks for any help!
08-Aug-11 07:51
@mbarcala @theaxnyc: Please post your questions in new topics:

http://www.elated.com/forums/authoring-and-programming/topic/new/

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
08-Aug-11 08:52
ok... but my post did pertain directly to this thread... i think, perhaps, i will need to place a link back to this thread in my new one as this was my starting code.?
27-Aug-11 13:15
Hi Matt,

I've got a problem in setting charset = "utf-8"
How do you insert the charset = "utf-8" to the processForm.php

Thanks


<?php


// Define some constants
define( "RECIPIENT_NAME", "david" );
define( "RECIPIENT_EMAIL", "....@msn.com" );
define( "EMAIL_SUBJECT", "coment" );

// 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 {
?>
<!DOCTYPE HTML>
<html lang="pt">
<head>

<title>Obrigado</title>

<meta charset="utf-8">
</head>

<body>

<?php if ( $success ) echo "<p>Obrigado pelo seu comentário</p>" ?>
<?php if ( !$success ) echo "<p>Houve um problema no envio do email. Tente novament.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>

</body>
</html>

<?php
}
?>
28-Aug-11 18:13
i don't know what i am doing wrong. I am getting two problems.

1. The status message font colour is same as the status window. So cant see anything.

2. the message is stuck at please wait sending you email..
Then nothing happens.

pls . help

Anupam Thakur

--
hello
29-Aug-11 07:00
@xarkan: See http://www.elated.com/forums/topic/5263/ and make sure your contact form page has a <meta charset="utf-8" /> tag.

@anupam347: Please post the URL of your form in a new topic, along with a description of the problem:

http://www.elated.com/forums/authoring-and-programming/topic/new/

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
08-Sep-11 07:51
Can someone help me with adding SNTP authentication? Neat code btw
08-Sep-11 15:34
Hey matt..
First of all, hats off for such a good tutorial.!! Great work!!

I am having a problem with this tutorial. I am new to php and ajax..
I followed your tutorial as it is, but when I fill the form and click Send Email, I get the error message "Please complete all the fields in the form before sending." even though all fields in the form are filled.
Also the error message doesn't fade out.. Is there any additional step to do this.

Here is the link to my page having the contact form: http://kunalaggarwal.eu5.org/website/home/
Click the Contact button on top.

Thanks in advance.!!

And seriously, very nice tutorial. Thank You!!
08-Sep-11 18:25
@itz_tim_y0: You mean SMTP auth? You can do this with the PEAR Mail package:

http://pear.php.net/package/Mail/redirected

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
09-Sep-11 03:19
@Matt, cheers for that. Also, how would i put this on a contact page where the form is displayed by default?
10-Sep-11 05:53
Hey Matt..

I fixed the problem that I posted above. It was a small error on my part, I missed the id attribute for the name text field, that was causing the problem..

Now it works like a charm!!

Thanks a lot for this tutorial. Simply amazing!!
10-Sep-11 14:48
Hey Matt..

Sorry to trouble again, but can you please provide some help on how to include a reCaptcha in this form. I obtained my key from Google for the reCaptcha.

Basically, I need help with the CSS on how to align it properly.

Thanks again!!
12-Sep-11 05:27
@itz_tim_y0: Just take out the JavaScript lines that hide & position the form:


  $('#contactForm').hide().submit( submitForm ).addClass( 'positioned' );



    $('#contactForm').fadeOut();
    $('#content').fadeTo( 'slow', 1 );


etc...

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
12-Sep-11 05:29
@KunalAggarwal: Sure, just post your question in a new topic as it's veering away from the article's topic somewhat:

http://www.elated.com/forums/authoring-and-programming/topic/new/

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
20-Sep-11 13:47
Hi great Tut! looks great! works perfectly, on Safari, Opera, Chrome, Firefox..IE 7, on my iPad, android phone, Xoom tablet(yes I bought one)...however, IE 9 is giving problems. It loads on the bottom left side of the page...thnx in advance!

edit oh err - my site http://www.movilenglishhd.com/Que_es_Movil_English.html

[Edited by Mark5555 on 20-Sep-11 13:48]
23-Sep-11 03:16
@Mark5555: Nice site!

You need to use the HTML5 doctype to stop IE9 going into quirks mode.


<!doctype html>


--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
24-Sep-11 10:45
Awesome! and thnx! I was going nuts with .noconflict() , css ie hacks..
Thnx again Matt!
28-Sep-11 02:27
@Mark5555: No problem - glad I could help

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
04-Oct-11 20:52
Very cool, except I'm having a problem when I try adding checkboxes to the mix. I've tried a number of things, but this is the way I figure would make the most sense.


<li>
<label>San Francisco</label><input type="checkbox" name="league" id="league" value="SF">
</li>


I just want the checkbox to appear on the same line right after the text, but when I do this the checkbox literally ends up right on top of the text. I'm sure I need to make some kind of change to the stylesheet, but I haven't been able to figure it out.
05-Oct-11 01:17
@sjsnider: Try adding something like this to your CSS:


input[type="checkbox"] {
float: left;
margin: .6em 0;
}


--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
05-Oct-11 01:40
Thanks so much. That was very helpful.
08-Oct-11 07:13
Hi I was wondering if there is an example using a captcha field to prevent non human sending.

I have a site that has this problem so want to use somethng like this cool example.

I also need to bring in another field to send the form to someone else but thats another story

so thought I would start with the captcha first any ideas?

Thansk for a great article and example

Andrew

--
Be good and nice to people and you wil get the same back.
11-Oct-11 19:08
I too am trying to use recaptcha with this to no avail. Can I get a little help?
12-Oct-11 06:54
@amcoms: Shouldn't be a problem. There are many captcha scripts that you should be able to integrate, eg:

http://www.phpcaptcha.org/

There's also reCAPTCHA which has plugins for various server-side languages and software, as well as a nice Ajax API:

http://code.google.com/apis/recaptcha/docs/display.html

@mydudechris: Sure, I'll try anyway! What problem are you having exactly?

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
24-Oct-11 12:50
hi,
how can i do it over flash?
26-Oct-11 13:04
Hi Matt

Firstly thanks for a well written and easy to follow tutorial.

I'm doing a site for free for my children's primary school, and when I test it on my own websites server it works fine but as soon as i transfer it to their server it goes through the motions and thanks me for sending etc but I don't receive the email?

I'm guessing that their server doesn't handle ajax or it's not enabled - is there anything else it could be?

Thanks again

P.
27-Oct-11 17:42
This is a great tutorial,
I have one problem though, I am not recieving any emails from the form, I have never made one of these before so I am clueless as to where the .php file goes, I just dumped it in with all the others and specified my email address in constants, what am I doing wrong ?

--
Tony
28-Oct-11 23:39
Hi,

I want to make a multiple choice quiz of 100 questions using javascript or php .
i want that when user fill the answer & submit it . The no. of correct , wrong & left answers (including correct answers) & score shown in the next tab .

can anyone help me ? Plz , its very urgent....
Thanx in advance.
01-Nov-11 12:28
This is the best tutorial I've ever seen on writing code of any kind. You do it right, Mr. Doyle!
02-Nov-11 01:57
@pixelist: More likely a mail server issue - it's not getting to your server's MTA, or the MTA is having trouble delivering it. This is a bit out of the scope of my article I'm afraid. You can post the problem in a separate topic if you like:

http://www.elated.com/forums/authoring-and-programming/topic/new/

@tonyb67: Same answer! The email is likely getting sent by the PHP script, but then the MTA isn't delivering it for some reason. If possible, check your PHP error log and/or your MTA's mail log to see if you can narrow down the issue. Do other PHP email scripts on the server send mail OK from and to the same addresses?

@AustinTxous: Thank you sir!

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
02-Nov-11 08:30
Hi Matt and Tony B

Thanks for getting back to me. I think it is a server problem - other php mail scripts work fine using the same address so it appears that it doesn't like the ajax?? On my own server the form functions as expected.

As this is an Education Authority server everything is slow and the Administrator has not even got back to me.

So I've gone back to a simple php mailer with redirect for the time being - can't thank you enough for your help though

Cheers!

P
02-Nov-11 09:21
Excellent work! 5 out of 5 stars! Clean and relatively straightforward to customize.
07-Nov-11 00:19
@pixelist: As far as web servers are concerned, Ajax requests are no different from regular HTTP requests. I don't think Ajax is your problem. I expect your PHP script isn't running correctly. You could try adding some debugging to the PHP script to see where the problem is.

You can also try disabling JS in your browser then reloading the page to get the non-Ajax fallback form, then try submitting that. That might give you a better idea of what's happening to your PHP script.

@jb0063: Thanks for the compliment

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
07-Nov-11 17:34
Hi,

I've been reading your articles and they have helped me BIGTIME! I really like this lightbox form, its fantastic but I am trying to add a captcha that I use in some of my other forms and I'm getting nowhere! Please could you help me with it!? I can show you what I've done so far ...

Keep up the killer work!!
11-Nov-11 03:25
@reflex84: Sure, please post your question in a new topic and we'll see if we can help!

http://www.elated.com/forums/authoring-and-programming/topic/new/

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
16-Nov-11 12:33
Greetings Matt;

Great tutorial, it seems to do exactly what I'm looking to do. I've tweaked a few things to reveal hidden layers rather than simply feeding the info. It seems to work as far as I can tell, but it hangs on the "sending" message and nothing comes through the email.

I have reverted to your php script, thinking that it may have been a mistake in my code, it doesn't work either. Other php mail scripts work on this server, so I don't know what it could be. Any help would be appreciated.

the URL is here, still using your demo.

http://betyar.comeze.com/Slick.html


Thanks.
17-Nov-11 16:16
Greetings again Matt;


Update. Don't know what was wrong, I started over from scratch and now it works.

One thing I was wondering though; I am clearing the form fields on "success", I was wondering how I could delay that action though. Using the same delay tag for
val( "" )
doesn't delay anything.

A little help?
18-Nov-11 01:12
@IBetyar: Your URL doesn't work for me (takes me to a hosting signup page).

You can use setTimeout to create a delay:

http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

Hope that helps!
Matt

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
18-Nov-11 07:12
thanx for nice tutorial..

i m trying to add Mobile No. below email ID but i m unable to customize... please help with mobile no.

--
nothing
18-Nov-11 07:15
here is my edited php code for mobile no.

<?php

// Define some constants
define( "RECIPIENT_NAME", "Site Form" );
define( "RECIPIENT_EMAIL", "mymail@mail.com" );
define( "EMAIL_SUBJECT", "Visitor Message" );

// 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'] ) : "";
$senderEmail = isset( $_POST['senderMobile'] ) ? preg_replace( "/[^\.\-\_\a-zA-Z0-9]/", "", $_POST['senderMobile'] ) : "";
$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 . ">" " <" . RECIPIENT_MOBILE . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">" . " <" . $senderMobile . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}

// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
} else {
?>

--
nothing
18-Nov-11 17:06
Hey Matt;

Thanks for the reply. That page got taken down after I resolved the problem. Sorry.

I couldn't get the delay to work on closing, so I simply cleared the fields when the user re-clicks to reopen the form. That worked. I will look into your suggestion though, it is definitely more graceful.

I do however have another problem, I have emailed you the details of the problem, as well as the proper link to your email from this site.

Thanks.
21-Nov-11 23:49
@avdhesh: What is the problem or error message that you're getting?

@IBetyar: Sorry, I only answer tech queries in the forums, not via email. You can post your problem in a new topic if you like:

http://www.elated.com/forums/authoring-and-programming/topic/new/

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
21-Nov-11 23:59
problem i s when i fill up mobile no. its shows email is not valid

--
nothing
22-Nov-11 05:49
can anybody provide me code with mobile no. verification please

--
nothing
23-Nov-11 20:44
@avdhesh: You have at least 1 bug in your code.


$senderEmail = isset( $_POST['senderMobile'] ) ? preg_replace( "/[^\.\-\_\a-zA-Z0-9]/", "", $_POST['senderMobile'] ) : "";


should be:


$senderMobile = isset( $_POST['senderMobile'] ) ? preg_replace( "/[^\.\-\_\a-zA-Z0-9]/", "", $_POST['senderMobile'] ) : "";


--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
24-Nov-11 02:15
still the same

and also mobile no. shud not accept aplha value....... but now its accept aplha....

i notice this while i send the message :-

There was a problem sending your message. Please try again.

--
nothing
25-Nov-11 04:51
@avdhesh: I can't see any other obvious problems from just looking at your code. You'll need to add some debugging to your PHP script. e.g. use echo to display the values of variables at various points, and see which variables are (or aren't) receiving the values from the form.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
29-Nov-11 05:41
Hi, im trying too use this script. Only thing is ive changed the buttons from send email too Skicka (Swedish for Send).

But when Ive made all inputs and press "Send" It says the message "please hold while we send the email" and it never sends the email.

If its at any help I use one.com as host and hotmail as recceiver.

Id like if you can send me a tip over email or something. Gonna try look over the code today and see if I can find something. But else I must say this is the nicest thing ive ever seen. Hope you will make more things like this for the community.

WibbenZ
Email: Wibbenz@gmail.com
01-Dec-11 03:14
@wibbenz: So you just changed the line:


<input type="submit" id="sendMessage" name="sendMessage" value="Send Email" />


to:


<input type="submit" id="sendMessage" name="sendMessage" value="Skicka" />


?

If so then I can't see any reason why this would break the script.

Try changing it back to:


<input type="submit" id="sendMessage" name="sendMessage" value="Send Email" />


Does it work now?

Cheers,
Matt

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
01-Dec-11 12:32
Hi - great stuff- its been working great..Initially I had a little issue making it run on IE, it was a bone head move by me, which you helped me fix..

I fear I've gotten too ambitious and got my self into trouble again..I got 4 jQuery plug-in/Libraries working at the same time

Nivo Slider
Lightbox
ThickBox (for videos)
Contact form...

I ve done some jQuery.noConflict(); tinkering to get them all to work, and it works great on Safari, Opera, Chrome, Firefox..except for, ofcourse IE..

its not hiding the form, it displays it on the bottom of the page

if you have some time could you look over my frankensteinian code, and see what might be the issue?

http://www.movilenglishhd.com

THNX again
05-Dec-11 17:38
I Love this!

Is there a way to add Section Drop downs sections with different options to it???



Thanks!
05-Dec-11 22:49
Can anyone answer this question pertaining to this ajax contact form not focusing in firefox when you have embedded divs?

http://www.elated.com/forums/topic/5351/

[Edited by altaone on 05-Dec-11 22:49]
06-Dec-11 01:56
@Mark5555: Try turning on IE Developer Tools (F12) and see if you get any errors in the JavaScript console. If there are no errors, try inserting console.log() calls at various points throughout the script to see what's getting run, and what isn't. For example, it may be that an event handler isn't firing in IE for some reason.

@mylifeinfiction: Thanks! Not sure what you mean by "Section Drop downs sections". You should be able to add in a <select> menu fairly easily if that's what you mean?

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
06-Dec-11 02:00
Yes thats what I meant a <select> menu
06-Dec-11 13:19
Hello Matt;

So I have been tinkering with the StopPropagation and event.preventDefault click handlers as you suggested. I am new at this and am probably still doing something wrong. I couldn't get it to work.

I gave up on using that scroller and opted to remove the offending conflicting scroller and am now using a Parallax type BG scroller. It works much better and no conflict.

Thank you for your patience and all of your help with this endeavour.
07-Dec-11 01:49
Hi, Matt!

After working on your tutorial for the whole day I was able to modify the code to fit my web site. It work amazingly! No more hours of digging for code!!!

However, I run into a couple of issues that I cannot resolve and am in need of your help, if I may.

1. When I receive a response from the mail form, in the field "From" I see my own E-mail address and not the name of the sender. Also, when I click "reply" I only see my own E-mail address. For some reason information from fields "senderName" and "senderEmail" getting lost (I attached all the codes below). Any idea what am I doing wrong?

2. I installed HTML code in one of the main content window of my web site (www.25bits.com). Everything works OK only if the "contact us" hyperlink is located in the same DIV. How can I move the hyperlink to any other place on the website?

Steven

HTML code:


<!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" />
<!-- TemplateBeginEditable name="doctitle" -->
<title>Welcome to 25 Bits!</title>
<!-- TemplateEndEditable -->
<!-- TemplateBeginEditable name="head" -->
<!-- TemplateEndEditable -->
<link href="_css/main_25bits.css" rel="stylesheet" type="text/css" /><!--[if lte IE 7]>
<style>
.content { margin-right: -1px; } /* this 1px negative margin can be placed on any of the columns in this layout with the same corrective effect. */
ul.nav a { zoom: 1; } /* the zoom property gives IE the hasLayout trigger it needs to correct extra whiltespace between the links */
</style>
<![endif]-->
<script src="Scripts/swfobject_modified.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="http://code.vostrel.cz/jquery.reel-bundle.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>

<!--Begins Mail Form Script -->

<script type="text/javascript" src="jquery-1.7.1.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() {
$('#content').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();
$('#content').fadeTo( 'slow', 1 );
} );

// When the "Escape" key is pressed, close the form
$('#contactForm').keydown( function( event ) {
if ( event.which == 27 ) {
$('#contactForm').fadeOut();
$('#content').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
$('#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
return false;
}


// 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>

<!--Ends Mail Form Script -->

<style type="text/css">



body {

background-repeat: repeat;
}
</style>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<!--Google Analitics -->
<script type="text/javascript">

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-27390220-1']);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

</script>
<!--End Google Analytics -->
<link href="_css/Styles.css" rel="stylesheet" type="text/css" />
</head>

<body>

<div class="container">
<div class="header">
<object id="FlashID" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="20%" height="90">
<param name="movie" value="Logo_25bits_3.swf" />
<param name="quality" value="high" />
<param name="wmode" value="opaque" />
<param name="swfversion" value="6.0.65.0" />
<!-- This param tag prompts users with Flash Player 6.0 r65 and higher to download the latest version of Flash Player. Delete it if you don’t want users to see the prompt. -->
<param name="expressinstall" value="Scripts/expressInstall.swf" />
<param name="SCALE" value="exactfit" />
<!-- Next object tag is for non-IE browsers. So hide it from IE using IECC. -->
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="Logo_25bits_3.swf" width="20%" height="90">
<!--<![endif]-->
<param name="quality" value="high" />
<param name="wmode" value="opaque" />
<param name="swfversion" value="6.0.65.0" />
<param name="expressinstall" value="Scripts/expressInstall.swf" />
<param name="SCALE" value="exactfit" />
<!-- The browser displays the following alternative content for users with Flash Player 6.0 and older. -->
<div>
<h4>Content on this page requires a newer version of Adobe Flash Player.</h4>
<p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" width="112" height="33" /></a></p>
</div>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>
</a>
<!-- end .header --></div>
<div class="sidebar1">
<ul class="nav">
<li><a href="equipment.html">Equipment for Rent</a></li>
<li><a href="#">Productions</a></li>
<li><a href="#">Photo Gallery</a></li>
<li><a href="#">Casting</a><!-- end .sidebar1 --></li>


</ul>

</div>
<div class="content">
<h1>While this site is still under construction, &quot;Equipment for Rent&quot; section is ready.</h1>
<p>Call us at 253-217-2377 with all your rental needs or <a href="#contactForm">contact us</a> via E-mail.</p>
<div><form id="contactForm" action="processForm.php" method="post">

<p>Send Us an E-mail...</p>

<ul>

<li>
<label for="senderName">Name:</label>
<input type="text" name="senderName" id="senderName" placeholder="Please type your name" required="required" maxlength="50" />
</li>

<li>
<label for="senderEmail">E-mail:</label>
<input type="email" name="senderEmail" id="senderEmail" placeholder="Please type your email address" required="required" maxlength="60" />
</li>

<li>
<label for="message" style="padding-top: .5em;">Message:</label>
<textarea name="message" id="message" placeholder="Please type your message" required="required" cols="80" rows="10" maxlength="10000"></textarea>
</li>
</ul>
<p>
<input type="submit" id="sendMessage" name="sendMessage" value="Send" />
<input type="button" id="cancel" name="cancel" value="Cancel" />

</p>
<p>&nbsp; </p>

</form>
</div>

<div id="sendingMessage" class="statusMessage"><p>Sending your message. Please wait...</p></div>
<div id="successMessage" class="statusMessage"><p>Thanks for sending your message! We'll get back to you shortly.</p></div>
<div id="failureMessage" class="statusMessage"><p>There was a problem sending your message. Please try again.</p></div>
<div id="incompleteMessage" class="statusMessage"><p>Please complete all the fields in the form before sending.</p></div>
</div>
<div class="footer">
<p class="footer"><a href="terms.html">Terms of Use</a> Privacy Notice Legal</p>
<!-- end .footer --></div>
<!-- end .container --></div>
<script type="text/javascript">
swfobject.registerObject("FlashID");
</script>
</body>
</html>



PHP code:



<?php

// Define some constants
define("RECIPIENT_NAME","Steven Mahoney");
define("RECIPIENT_EMAIL","steven@25bits.com");
define("EMAIL_SUBJECT","Visitor Message");

// 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 . ">"; */
$headers = "From: " . $senderName . " <" . RECIPIENT_EMAIL . ">" . "\r\n" . "Reply-to: " . $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>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>


and I haven't changes anything else.
07-Dec-11 11:03
Thanks for answering my other question. You've been great. as is the site.

I have one more as I am really new at PHP.

Would the following code be correct if I want to add a phone field? I found this online.




$phone = isset( $_POST['phone = preg_replace("/[^0-9]/", "", $phone);

if(strlen($phone) == 7)
return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
elseif(strlen($phone) == 10)
return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1)$2-$3", $phone);
else
return $phone;
07-Dec-11 11:39
Great - Thnx again!!
09-Dec-11 03:16
@mylifeinfiction: Cool, just add your <select> element and style it in the CSS. You can read its value in your PHP handler just like the other fields. eg:


<select name="mySelect"> ... </select>


and...


$mySelect = isset( $_POST['mySelect'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['mySelect'] ) : "";


The value of the selected option will be passed to $_POST['mySelect'] in the PHP.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
09-Dec-11 03:39
@IBetyar: Glad you got a solution in the end

@stevenmahoney:

1) It's because you've commented out the correct line of code:


/* $headers = "From: " . $senderName . " <" . $senderEmail . ">"; */


and replaced it with:


$headers = "From: " . $senderName . " <" . RECIPIENT_EMAIL . ">" . "\r\n" . "Reply-to: " . $senderEmail;


...which will send the mail from your email address instead (RECIPIENT_EMAIL).

2) What happens if you move the hyperlink outside the div? Can you post the URL of a page that has the problem you mention?

Cheers,
Matt

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
11-Dec-11 08:06
I tried to add some spam measures and they did not work properly.

anyone know how to fix?




// anti-spam time delay check
if((strlen($time_delay[$config]) > 0 && strlen($_POST["time"]) > 0) || (strlen($time_delay[$config]) > 0 && (strlen($_POST["time"]) == 0 || !$_POST["time"])))
{
if((time() - $_POST["time"]) < $time_delay[$config])
$time_message = "<li>This has been stopped by the timer, and is likely spam.</li>\n";
}

/////////2nd method
// anti-spam max URL check
if(strlen($max_url_fields[$config]) > 0)
{
$max_url_message="";
$field_check=preg_split('/,/',$max_url_fields[$config]);
$field_run=sizeof($field_check);
for($i=0;$i<$field_run;$i++)
{
$cur_field_name=$field_check[$i];
$cur_field=$_POST[$cur_field_name];
preg_match_all("/http:/", $cur_field, $matches);
if(count($matches[0]) > $max_urls[$config])
$max_url_message.="<li>This message contains too many URL's.</li>\n";
}
}


I also could not get it to truly check for proper email format using:



$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderEmail'] ) : "";


I input about 20 random alpha characters and it still got through in the email area as did 3 urls in the msg area.

Thanks
11-Dec-11 17:04
@altaone: No, I doubt that would work. This isn't even valid syntax:


$phone = isset( $_POST['phone = preg_replace("/[^0-9]/", "", $phone);


I assume the other block of code is to filter and reformat phone numbers? Looks like it should work, although you don't want to return the results of preg_replace(). Assign them to $phone instead.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
11-Dec-11 17:34
hello and thank you very much for this tutorial,
i hope that you've got time to respond to this stupid question

If for example I'm adding a field for phone number like this:


<li>
<label for="telephone">Votre téléphone </label>
<input type="text" name="telephone" id="telephone" placeholder="tel" required maxlength="14" />
</li>

What i have to change into processForm.php, if i want to receive this phone number into the message body .
sorry for my frenchglish and thanks
11-Dec-11 17:41
@altaone: This topic is for questions about the code in the tutorial. If you need help with an anti-spam system, please post your question in a new topic, with a description of any error(s) and the URL of the problem page:

http://www.elated.com/forums/authoring-and-programming/topic/new/

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
11-Dec-11 17:47
@truitas:


$telephone = isset( $_POST['telephone'] ) ? preg_replace( "/[^\ \-0-9]/", "", $_POST['telephone'] ) : "";

...

$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";

$message .= "\n\nTelephone: $telephone\n\n";


etc...

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
11-Dec-11 18:00
thanks for this quick response, it's working well....
15-Dec-11 11:18
Hi,

I hope you can help. I'm trying to incorporate this excellent code into a website i'm working on.

I have jquery working to rotate images in the header of the website. However when I click the email us link, the form appears under the rolling images?

Also when I click Send Email, it says "Sending your message. Please wait..." but nothing happens from here?

Any ideas? heres the link: http://d1358011.ali41.something.ie/

thanks
16-Dec-11 05:56
Matt?
Hi dude.

I have a weird issue.
Those lines doesn’t work at all:

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

I don’t understand since if I ask to show it instead of hide the form when the page loads, it works.

It works too if I put $('#contactForm').show()...

(note that #centre is my content wrapper)
I can see it and it works.

#center #contactForm are not fading at all and the form is not being displayed. ???

I’ve no more ideas now to fix that issue.
Do you have one?

Thanks for your reply, Matt.

[EDIT] Oops. Forgot to tell .positioned class is never added to the form. Even in your demo.
Do I misunderstand something?

[EDIT 2] I’ve tried with your jQuery link (mine was using the latest] with the same result.
As I made working easily on a stand alone page a few month ago, I don’t see why it can’t work in the CMS I use (which is using XML for storage instead of a database).

[Edited by Sventovit on 16-Dec-11 09:50]
19-Dec-11 23:05
@spencer: I couldn't view your URL ("Error establishing a database connection"). Also, might be best to post in a new topic since your question isn't about the original tutorial code:

http://www.elated.com/forums/authoring-and-programming/topic/new/

@Sventovit: Please post the URL of the page with the problem, so we can see it in action.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
20-Dec-11 09:46
Hello Mr Matt
thanks a lot for having replied.

I just sent the files and now the whole enchilada is online.

This is the URL of the blog home page :
-http://sventovit.fr/logbook/

The box should open when clicking on the #contact menu in the nav section. (-http://sventovit.fr/logbook/#contactForm)

I’m really sorry to annoy ya with such an issue. I’ve spent about 2 hours to make it work and nope: I just still can’t see where my error is.
Maybe you’ll find it…
Thanks again.
Phil
22-Dec-11 00:39
This tutorial is awesome, can you tell me how to make a zip file download when the form is submitted.

I assume it would be some kind of if statement in the PHP, but I am not sure exactly what to say there.

It would be very helpful if you could tell me how to do that.

--
a hrefhttp://blazestudios.bizBlaze Studios Designs/a
22-Dec-11 04:32
Thanks a lot for this nice submit form!

I have one question, how can i refresh DIV 'content' when de form is succesfull submittet?
22-Dec-11 13:41
I figured it out, I just put:

window.location.href = "images/download/file/name"; in the if/else statement at the end. Works perfect now.

--
a hrefhttp://blazestudios.bizBlaze Studios Designs/a
31-Dec-11 20:07
VERY nice form!
I have a question: the #incompleteMessage seems to be unused, it will never appear in any situation. Instead, an image pop up with the words "please fill out this field" will appear if I leave anything blank. This occurs for both your demo and after I implemented it in my website. I don't really mind as I think "please fill out this field" right below the field that needs filling is more useful, but I can't seem to change this message (can't find anywhere within css/html/php file that produces this pop-up).
Thanks for your help!
02-Jan-12 08:50
i have a same problem like windbrand ;
how can i change the "please fill out this field" phrase ?
and i want change the css of this phrase. please help . its necessary
06-Jan-12 02:04
Hi Matt
what should I do now?
06-Jan-12 02:55
@Sventovit: First thing that springs to mind is that your Contact link's href attribute is:

"http://sventovit.fr/logbook/#contactForm"

But you're trying to select it with:

$('a[href="#contactForm"]')

I'd wager that jQuery's selector engine sees these as 2 different URLs.

Try:

$('a[href="http://sventovit.fr/logbook/#contactForm"]')

instead.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
06-Jan-12 03:31
Hi Matt
thanks for having replied. I much appreciate.
Your suggestion does it… on the blog home page and only on it.

If the visitor lands on an article page, the URL won’t be the same (eg ../logbook/article15/balisage-semantique-gabarit-html5-over/#contact) and the contact form won’t be displayed.
Weird, isn’t it?

Does that mean your script will only work on a "stand alone page"?
Regards,
Philippe

EDIT: there was a typo.

[Edited by Sventovit on 06-Jan-12 06:24]
06-Jan-12 07:11
hi,
your form is working well, but i've got some problems with special characters: ' à, é, è, ü etc .

Fore example the word l'activité will appear like this into the message body: l\'activité

How i can solve this?

thanks
06-Jan-12 07:33
By saving the php file "processform" in UTF-8 without BOM maybe?
06-Jan-12 08:46
thanks, but i think that's a problem between utf8 and iso, i found this:
the page displays the characters of this type: "Ã ©", "Ã ®", "A" ...
=> The data was saved in UTF-8 format = the browser think it is
ISO format.

the page displays the characters of this type : "�"
=> The data was saved in ISO format = the browser think it is
UTF-8.

PHP natively work in ISO, it will switch entirely to UTF-8 after v6.
11-Jan-12 16:32
@windbrand: What you're seeing is your browser's HTML5 form validation, triggered by the "required" attributes in the form's fields. It is browser-specific. As far as I know, you can't alter the message that the browser displays. #incompleteMessage is used as a fallback if the browser doesn't support HTML5 validation.

If you'd rather just use the #incompleteMessage validation at all time, remove the "required" attributes. Personally I'd use the HTML5 validation if the browser supports it.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
11-Jan-12 17:25
@Sventovit: I would try making all your Contact links just point to the URL:

"#contactForm"

Then the URL will be the same on all documents, and you can select the link with:

$('a[href="#contactForm"]')

You will of course need to include the contact form JS in every HTML document in your site.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
11-Jan-12 17:39
@truitas: Make sure you use UTF-8 encoding throughout the whole chain: include <meta charset="utf-8">in the HTML document; serve the document with the "Content-Type: text/html; charset=utf-8" HTTP header; and set the MIME content type in the email body to "text/plain; charset=utf-8".

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
12-Jan-12 03:51
This is the original code which doesn’t work Matt.
16-Jan-12 02:37
@Sventovit: I don't understand your response. Are you saying there's a bug in the original code?

You need to include the JavaScript and markup for the contact form on every page where you want to use it.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
16-Jan-12 07:40
I meant "which doesn’t work" on dynamic URL.
I can’t say there’s a bug in the original code as I’m not skilled enough. I know it’s working on a single page but there’s an issue with such URI.
17-Jan-12 18:19
Hello Matt,
Thank you for the post it is really interesting and well explained. I was able to make it work alone, but now I am trying to implement the ajax animation in another form. Trying to get the notifications and fadein, fadeTo effects.
But I am having problems with this part of the code:

// 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>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}

Im always getting the answers:
"There was a problem sending your message. Please try again."

how can i check where is the problem, I know its not a precise question, but maybe you can help me.
17-Jan-12 21:29
what is the difference between?

define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

and

if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
} else {

Why and when use each one?

Thanks again
17-Jan-12 23:36
This is the message to all participants and guests of this blog. After spending a couple of months playing with the code provided here, I was able to figure out why my code did not work and I was able to fix it.

Here is what the problem was: server restrictions. It appears that different sites impose different restrictions or rules as to how PHP handled. (some do not allow "mail" command, some restrict the way you define functions, some impose an obligatory code you have to use, etc.) Absolutely same code would produce different result, depending on your web server.

After pulling my hair, I began shopping around and was able to find a free web hosting, that has very few restrictions. And, voila! - the code works without a glitch!

I hope this message will help others and eliminate frustration.

I am not a professional coder, so, please excuse me if I sound like an amateur.

Steven
19-Jan-12 23:30
@Sventovit: I'm not familiar with how your site navigation works, but in theory there's no reason you couldn't use the contact form script on your site. If you're using some JavaScript code for your navigation then you might need to rewrite some of the contact form code to play nicely with it. I'd guess that there's some conflict between the contact form code and your navigation code.

Try adding console.log() throughout the contact form code to see which bits (if any) are being run when you click the Contact link.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
19-Jan-12 23:55
@bernardao: Could be a number of things. As @stevenmahoney points out (thanks Steven!) it could be a server restriction. It might also be that the PHP script isn't getting the data correctly from the form. See here for some troubleshooting tips:

http://www.elated.com/forums/topic/5171/#post20765

HTTP_X_REQUESTED_WITH refers to the X-Requested-With header sent by most JS frameworks along with an Ajax request. It does much the same thing as my code, but it does depend on the framework sending the header (and the web server allowing PHP to access the header). More here:

http://stackoverflow.com/questions/2579254/php-does-serverhttp-x-requested-with-exist-or-not

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
20-Jan-12 09:51
Mr Matt?
Hello.
I didn’t find the reason of this issue but I fixed it by changing the onclick call this way:

$('a[href="'+self.location.href.split('?')[0]+'#contactForm"]').click( function() {

And now, tada! It works everywhere.
Thanks a lot for your patience and kindness.
I really appreciate.
20-Jan-12 11:03
Oh! I forgot to test the sending and it fails.
I’m having the message:
"There was a problem sending your message. Please try again."
Is it due to my code?
23-Jan-12 00:31
@Sventovit: See here for some tips for troubleshooting the mail sending:

http://www.elated.com/forums/topic/5171/#post20765

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
23-Jan-12 05:50
It’s a bit more complicated since it works on the blog home paginated page and not on a the single page of an article.
And there I don’t see why the form doesnt’ work.
27-Jan-12 00:24
@Sventovit: Put some debugging in your PHP script to see what data the script is receiving from the form. Then see what happens when you post the form on both the blog home page and on the single article page. Does the PHP script receive the data correctly in both cases?

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
31-Jan-12 11:17
Hey everyone,
I am new jquery(new as in one day old). I cannot get this working even if I just download the code and modify the PHP file so that it has my email it does not work. So help? I have a gmail email address.
Thanks.
02-Feb-12 22:56
@isheets: You need to give more information - what doesn't work exactly? Do you get any error message?

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
03-Feb-12 10:16
Hi Matt!

Thanks for posting this wonderful tutorial!

Because I'm using a form with many more inputs (and for extra security), I prefer to use Tectite's FormMail script for handling the form.

However, one major disadvantage of Tectite's FormMail is that it doesn't support AJAX form submission out of the box. I spent a few hours integrating your JQuery script with Tectite's FormMail and thought I'd share the result for anyone else interested!

I just inserted the AJAX browser response lines before the FormMail script redirects to the Thanks page. In my FormMail.php file, the code to redirect is on line 13482

CreatePage(GetMessage(MSG_THANKS_PAGE),GetMessage(MSG_FORM_OK));

With your AJAX browser response code inserted, the code now looks like this:

if ($bGotGoodTemplate){

if ( isset($_GET["ajax"]) ) {
$success = 1;
echo $success ? "success" : "error";
} else {
OutputTemplate($SPECIAL_VALUES["good_template"],$aRawDataValues);
}
}
else {
if ( isset($_GET["ajax"]) ) {
$success = 1;
echo $success ? "success" : "error";
} else {
CreatePage(GetMessage(MSG_THANKS_PAGE),GetMessage(MSG_FORM_OK));
}
}


I'm also using my own Thanks page instead of Tectite's auto-generated one, so I inserted the AJAX browser response code before the Thanks Page template is called.

I also used the jQuery serializeArray() method instead of serialize() in order to include hidden inputs from the form, which is crucial to the functionality of FormMail.

It took me a few hours to figure it out, and since I got it working, I thought I'd share with others!
06-Feb-12 03:28
Hello Matt
thanks again for the support.
I’ve tried this weekend to "debug" and only found this error when trying to send a mail using the form on a single article page:
A session had already been started - ignoring session_start()
Hum…
06-Feb-12 12:00
Matt this is an awesome tutorial and i think you done great job!! I tested the form and it works like a charm.

One thing I want, if you can help me! I'm trying to fill the form with greek characters and the message appears weird. I scroll the messages and i saw that maruse also had the same issue with Japanese and he solve it! Unfortunately I don't know how to use the strip_tag(). If you can post a solution about, I will appreciate a lot!
Also, is it possible to write at fields John Smith and Visitor Message something in different language and appears correct??

Thank you!!
07-Feb-12 23:02
@kimbo6365: Great tip - thanks for posting

@Sventovit: Hmm, not sure. I'd have to see your whole PHP script. I assume you are calling session_start() in the script for some reason?

My guess is that, since your PHP script works on one page and not another, there's a problem in the second page (either in the form JavaScript, the markup, or some other conflicting JavaScript) that is preventing the data getting to the PHP script.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
07-Feb-12 23:33
@apokyro: Try just adding the 'u' flag to the calls to preg_replace(), as I describe here:

http://www.elated.com/forums/topic/5171/#post20818

Also make sure the HTML document containing the form uses UTF-8 encoding:


<meta charset="utf-8">


--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
10-Feb-12 05:03
Hey,

first thanks for this great script!

I added an extra field for a telephone number and a checkbox where the user can request to be called back.

Is there any possibilty for set the telephone-field to "required" when the checkbox is checked?

thanks for you help.
15-Feb-12 22:41
@68bydesign: Not using the HTML5 required attribute, but you could do it with JS inside the submitForm() function. eg:


if ( $('#callback').attr('checked') && !$('#telephone').val() ) {
// Display alert
}


etc...

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
16-Feb-12 16:21
Hey Matt!

I followed your tutorial but I'd like to expand on it a little more to allow attachable files and a few other fields. Can you help me do this? I am having quite the time figuring out why it isn't working for me.

My HTML


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.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() {
$('#content').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();
$('#content').fadeTo( 'slow', 1 );
} );

// When the "Escape" key is pressed, close the form
$('#contactForm').keydown( function( event ) {
if ( event.which == 27 ) {
$('#contactForm').fadeOut();
$('#content').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
$('#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
return false;
}


// 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( "" );
$('#senderPhone').val( "" );
$('#message').val( "" );
$('#senderResume').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>

</head>
<body>

<div class="wideBox">

<h2>Marksmen Vegetation Employment Opportunities</h2>
</div>

<div id="content">

<p style="padding-bottom: 50px; font-weight: bold; text-align: center;"><a href="#contactForm">Click Here to Submit a Resume</a></p>


</div>

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

<h2>Submit a Resume online</h2>
<p>Please ensure you select the appropriate job opportunity. Only those selected for an interview will be contacted.</p>

<ul>

<li>
<label for="senderName">Your Name</label>
<input type="text" name="senderName" id="senderName" placeholder="Please type your name" required="required" maxlength="40" />
</li>

<li>
<label for="senderEmail">Your Email Address</label>
<input type="email" name="Email" id="senderEmail" placeholder="Please type your email address" required="required" maxlength="50" />
</li>

<li>
<label for="senderPhone">Your Phone Number</label>
<input type="text" name="Phone" id="senderPhone" placeholder="Please type your phone number" required="required" maxlength="10" />
</li>

<li>
<label for="message" style="padding-top: .5em;">Please paste your cover letter here</label>
<textarea name="textarea" id="message" placeholder="Please type your cover letter" required="required" cols="80" rows="10" maxlength="10000"></textarea>
</li>

<li>
<label for="senderResume">Upload resume in PDF format</label>
<input type="file" name="senderResume" id="senderResume" placeholder="Select a File" required="required" maxlength="50" />
</li>

</ul>

<div id="formButtons">
<input type="submit" id="sendMessage" name="sendMessage" value="Send Resume" />
<input type="button" id="cancel" name="cancel" value="Cancel" />
</div>

</form>

<div id="sendingMessage" class="statusMessage"><p>Sending your message. Please wait...</p></div>
<div id="successMessage" class="statusMessage"><p>Thanks for sending your message! We'll get back to you shortly.</p></div>
<div id="failureMessage" class="statusMessage"><p>There was a problem sending your message. Please try again.</p></div>
<div id="incompleteMessage" class="statusMessage"><p>Please complete all the fields in the form before sending.</p></div>



</body>
</html>




And my PHP which doesn't seem to grab my items and attach them.



<?php

// Define some constants
define( "RECIPIENT_NAME", "Field Manager" );
define( "RECIPIENT_EMAIL", "daryl@marksmeninc.com" );
define( "EMAIL_SUBJECT", "Website Resume Submission" );

// 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>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>

20-Feb-12 03:32
@delvok: If you're sending form data from a 'file' input type then you need to add the attribute enctype="multipart/form-data" to your <form> tag.

Also it doesn't look like you're capturing the uploaded data in your PHP script. You need to open the file stored at $_FILES['senderResume']['tmp_name'], read its contents, and attach it to your email message using something like the PEAR Mail_Mime package (give it a MIME type of "application/pdf").

More info:

http://www.php.net/manual/en/features.file-upload.post-method.php

http://pear.php.net/package/Mail_Mime/docs

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
20-Feb-12 14:59
This is a wonderful little tutorial, thank you for sharing it. It's very well written and easy to follow. I have asked my fiance to buy me the book!

I read the whole thing from start to finish and did all the steps in order with no problems. It was a complete success and I'm now looking at ways to incorporate this into a project I'm working on.

One question:
Do you have any other tutorials that would explain to me the basics of how to add conditional fields to the form? (i.e. if field A = 'yes', then additional fields are hidden/shown).

Or if it's not too much trouble, could you provide me with a basic example using this tutorial as a reference point? I catch on fairly well, so a code snippet would do.

Thanks again

EDITED:
I've done a bit of Googling and (after a bit of tinkering) solved my own question by applying the logic of some code explained in this other post --> http://anthonygthomas.com/2010/03/14/display-form-fields-based-on-selection-using-jquery/

Here is the the code I have put together, based on the original tutorial given above to demonstrate conditional show/hide fields within the Slick Ajax Form --> http://jsfiddle.net/r262B/1/

Happy days

[Edited by BunnyBomb on 21-Feb-12 10:08]
22-Feb-12 09:34
What an excellent tutorial. Thanks for the good work!

I implemented the contact form into my website, and all seems to be well except for a few minor things.

www.tosstemple.com

When I added the code for the contact form, the background I set for <html> seems to vanish. The first css rule pertains to setting the background to a full image, and while it worked prior to adding the contact form, it seems to now be in conflict.

Is there anything you guys see that could be blocking the background image from appearing? Any help would be greatly appreciated!

Thanks!

P.S. on an unrelated note, I'd also like to center images/finalbackground.jpg, but all the various css positioning techniques I've attempted have resulted in no dice. Any suggestions?

-J
22-Feb-12 11:08
I'm no expert but I took at look at your CSS and noticed a couple of obvious problems.

You have <style> tags within your CSS file, which seemed to make it about as useful as a ginger-haired-step-child. Also, the background image is being added to the <html> tag, which I'm told is not ideal. IE doesn't understand this, so it's best to use your <body> tag instead.

Here is a new version of your CSS file that does what you want:
http://pastebin.com/7GuQtW5Q

Lastly, the way you had included conditional statements at the end of your main CSS file won't work. I recommend creating a special file called "IE7styles.css" then adding code along the lines of this into your <head> tag within your html file:

<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="IE7styles.css" />
<![endif]-->


I'm no coder, but it's amazing what you can learn with a bit of fiddling around using Firebug.

Cheers


PS: I recommend adding a blank "index.html" file into your /images folder so folks can't see all your gibsons.

[Edited by BunnyBomb on 22-Feb-12 11:09]
22-Feb-12 14:33
Is it possible to modify this so that there are 2 different contact forms on one html page. I need one that is just a generic contact form like the demo to send to info@example.com and another contact form on the same page with one additional field (drop down field) that sends an email to specialorders@example.com. Any advice on how to accomplish this would be greatly appreciated.
thanks
22-Feb-12 18:32
Ahh, thanks so much BunnyBomb. Your advice helped me greatly and now everything is looking just peachy.

I hadn't heard of Firebug before, but will be sure to check it out.

Also, for the sake of learning, what does adding a blank 'index.html' file in the /images folder do such that it hides my gibsons?

-J
23-Feb-12 06:02
Glad to have helped.

Yeah I use a couple of things now, after doing some reading. I use two Firefox extensions called Firebug and Web Developer. Firebug is great for inspecting CSS via right click, to work out what the hell is going on. Web Developer is great for editing the CSS to generate a new CSS file (like I did for you in like...2 mins).

As for the blank index.html - before you added the file I could navigate directly to 'http://www.tosstemple.com/images/' and browse through every image file you had in that folder, save them down, etc. It's just best practice not to make it easy for folks to copy all your media in one click. Glad to see you added the file.

Best of luck
23-Feb-12 22:04
So here is an example of what I'm trying to do. http://twistedsisterscupcakes.com/Contact2.html
I can get the 2 different forms (contactForm, contactForm2) to pop up and fade out but neither will send an email. It says there is a problem sending your message. I moved the jquery from the html page to specialorder.js and contact.js. Does processForm.php need to be in the same folder as my Contact2.html? I have it in a different folder (php).
27-Feb-12 20:53
@BunnyBomb: That's a nice solution for adding conditional fields to the form - thanks for posting it

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
27-Feb-12 21:16
@dzoid11: It doesn't matter where your processForm.php script is, as long as the paths to processForm.php in your form tags are correct.

See my previous hints in this thread for debugging the email sending (search the page for 'debug').

Matt

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
28-Feb-12 13:52
@matt thanks.
I've got the first contact form working but the second one says "please complete all fields in the form before sending" even though all the fields are filled out.

I added ?ajax=true to the form action and turned off javascript in my browser. The first form returns "Thanks for sending your message! We'll get back to you shortly." and successfully sends the email. The second form returns "success" and successfully sends the email.

Any ideas on why the second form would send an email when java was turned off but not when it's turned on?
http://twistedsisterscupcakes.com/Contact2.html
29-Feb-12 22:33
Hi matt,

great stufff love it,,
also i have a question,, how to change tooltips "Please fill out this field" and "Please enter an email address" i can't find out this text on source,, am noob for this,, any help would be nice,,

Thanks,
01-Mar-12 04:52
@dzoid11: You can't just duplicate the form in the page, using the same id attributes, and expect the JavaScript to know which form it's working with. id attributes have to be unique in a document. Once you have unique IDs you'll also either need 2 different contact form scripts to work with the different ids, or modify the one script to accept a base id (eg "contact-" and "special-order-") that it then uses to determine the ids of the form fields it needs to work with.

@adoet_t: I already answered this earlier in the thread.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
04-Mar-12 15:28
Hi Matt,
Superb contact form, I've looked at many, and this was by far the best and easiest to implement.
I used it on my wife's site here:
http://namaste-naturaltherapy.com

It's working very well, but she is getting a lot of spam from bots,
Is it possible to implement some kind of anti spam measure, like a captcha?

Thanks

[Edited by Moog on 04-Mar-12 15:28]
07-Mar-12 04:24
hello matt...
Thanks for the amagind script... i am using your form for getting details from the customer before downloading the pdf.. so naturally no change in form page.. but when it throws to processForm.php i have to send details in database. that i done. but after that i hv to send pdf file to user for save. it works but ont in scusees mode.. and form is still appearing on the page..!!! one more thing pdf path is also come from database by the select query on the same page i.e processForm.php i dont required to send any email
here is the code for my processForm.php




<?php
include("config.php");
include("mysql.lib.php");


$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'] ) : "";
$productid = isset( $_POST['hiddenField'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['hiddenField'] ) : "";
/*$currenturl = $_POST['url'];*/
$query = "SELECT pdf FROM products where id=$productid";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$pdfpath = $row['pdf'];
}
$date = date('m/d/Y', time());

if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
}

mysql_query("INSERT INTO download (name,email,pdf,productid,downloaddate)
VALUES ('$senderName','$senderEmail','$pdfpath','$productid','$date')");
// force to download a file
$file = "http://localhost/oria/pdf/".$pdfpath."";
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

header("Content-Type: application/force-download");
header( "Content-Disposition: attachment; filename=".basename($file));

header( "Content-Description: File Transfer");
@readfile($file);
?>



i hv to submit this projet in my college so plz help me solve this matter as soon as possible thanks a lot...!!!
if u hv any doubt feel free to ask me...!!!
Akil Shaikh

[Edited by akilshaikh on 08-Mar-12 22:58]
09-Mar-12 18:00
@Moog: Have you tried reCAPTCHA? Should be fairly easy to integrate if you generate the contact form page in PHP:

http://www.google.com/recaptcha

@akilshaikh: The contact form JS expects an Ajax response (success/error), so sending back a stream of PDF data isn't going to work. I suggest you modify the JS so that, once it receives a "success" response, it redirects to your PDF:


window.location.href="http://pdf-url"


This can either be the actual PDF file, or a PHP script that serves the PDF data.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
10-Mar-12 00:35
Thanks Matt

thanks for quick reply.. but still i am little bit confuse. where should i write this code.. in jquery.min.js file
or
in my processForm.php page. after my insert query.
And after applying this i hv to write the php code for download file?
i try after insert query. it loads the pdf but in same the page. and not prompt to save .pdf file and user have to click back button of browser to go back to site.. u know its not user friendly.. so plz give me some hint about where should i have to write this code. i hope i am not bothering you.. i am littlebit new to js. so don't wont to take any-type of risk with the js file.. hope u understand that....
thanks a lot for your quick response

Akil Shaikh

[Edited by akilshaikh on 10-Mar-12 00:59]
10-Mar-12 17:49
Thanks Matt, it looks easy enough, though it will need some restyling to suit
15-Mar-12 07:13
Firstly what a slick form this is. I got it working quite promptly but when I validated it I got the following error, right over my head opinions would be most welcome. Best wishes Nick
W3C Mark up validator
Validation Output: 1 Error

Error Line 301, Column 75: value of attribute "type" cannot be "email"; must be one of "text", "password", "checkbox", "radio", "submit", "reset", "file", "hidden", "image", "button"

…ail Address</label> <input type="email" name="senderEmail" id="senderEmail" ma…



The value of the attribute is defined to be one of a list of possible values but in the document it contained something that is not allowed for that type of attribute. For instance, the “selected” attribute must be either minimized as “selected” or spelled out in full as “selected="selected"”; a value like “selected="true"” is not allowed.

[Edited by nicallen on 15-Mar-12 07:14]
15-Mar-12 16:22
Hello and nice work Matt!

is possible to offer us a little tutorial how i can use it in wordpress?

I've try allots of tricks but no results...

I'll be so happy if you can explain a bit

GJ!
18-Mar-12 02:10
Hi, i was wondering if you could advise on a small piece of code or link to incorporate this form to an existing website for instance i have different contact options on my site like ones an image then there is some text id like to link it too.

--
Half Full
20-Mar-12 01:29
@akilshaikh: In the JavaScript in your contact form page. Modify submitFinished() to redirect to the PDF URL if a "success" message is received. You don't have to use PHP; just upload your PDF file somewhere and let the web server serve it to the browser.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
20-Mar-12 05:41
Thanks for quick the reply Matt, unfortunately I've been trying without much success i know its probably very simple but i haven't been able to get it right could you please past the code for me and direct me were to slot it, otherwise i want be able to use this form for my website and i have to be honest I've seen a lot of contact forms but this is the mother of them all and really want to use it.

--
Half Full
22-Mar-12 02:04
Hello Matt..
First of all lot of thanks to you coz even in your busy schedule u spare time for solving the issues of people..
Now coming to my issue.. after your first solution i.e.


window.location.href="http://pdf-url"



i used it in my processForm.php like this



<?php
include("config.php");
include("mysql.lib.php");

$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'] ) : "";
$productid = isset( $_POST['hiddenField'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['hiddenField'] ) : "";
$query = "SELECT pdf FROM products where id=$productid";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$pdfpath = $row['pdf'];
}
$date = date('m/d/Y', time());


mysql_query("INSERT INTO download (name,email,pdf,productid,downloaddate)
VALUES ('$senderName','$senderEmail','$pdfpath','$productid','$date')");

if ( isset($_GET["ajax"]))
{
echo $success ? "success" : "error";
}
else
{
?>
<script language="javascript">
window.location.href="http://elevatormachine.in/pdf/<?php echo $pdfpath; ?>";
</script>
<?php
}
?>



Now when i apply this code pdf is downloaded successfully but it doesn’t want prompt to download and still open in same page. now you can see that this code work in else portion. so naturally success part is not working u can look at my site how i customize your form for my site here is the link

http://elevatormachine.in/productdetails.php?id=2

click on download pdf button u will understand what i want to achieve.

Now in your second reply u said that no change in php file. and change must be in JavaScript.

Now try to understand the flow of this from pdf path is static but pdf name is dynamic it comes from database with the help of product id. now when i use your code



window.location.href="http://elevatormachine.in/pdf/<?php pdfpath ?>"



Now what happen in this case form is simply display in product details page instead of dynamic display. i mean it appear bottom side of my product details page.(hope u got it)

Now one more thing when i remove message field from the validation i can’t get the value of email in database. (it’s strange for me).

Hope u are clear with this. If u have any doubts plz feel free to ask me.
so kindly help me for about this if u give any kind of hint or suggestion for solving this..

Lot lot thanks to you

Akil Shaikh

[Edited by akilshaikh on 22-Mar-12 02:06]
22-Mar-12 12:29
hi, great tutorial ive imbedded the model into an module in cmsms, and i thought id finished - but then realised that the validation processes on both sides client and server dont seem to work in IE7-9. your tutorial version does not either so I wonder if you have any ideas ?

javascripts are obviously running because the fadeouts and hiding work, as well as the ajax call and email processes, but in ie i can fill in garbage in the email field (the only field im using) and it passes right through to email, in chrome, firefox etc all works as expected

be very grateful for a suggestion

and thanks again for a great tutorial !
23-Mar-12 02:22
@nicallen: Sounds like you're not using the HTML5 doctype, and/or you didn't select the "HTML5 (experimental)" option for the Document Type option in the validator.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
23-Mar-12 03:14
thanks for prompt response, actually I have used the correct doc type but if i had not - that would not explain why your demo run from your site does not work either ! is there perhaps an issue with windows 7 and ie and the tutorial? i have tried running your demo from both a pc and a laptop and both allow rubbish through the email field and behave as though it is successful - running your demo from your site (eg here) in all other browsers seem to work as expected and the rubbish is stopped.

sorry to persist - it would be hugel-y useful to resolve this whatever the reason! many thanks
23-Mar-12 03:14
@Ferris: If you post the URL of your contact form in a new topic, as well as exactly what you want to achieve, then someone may be able to point you in the right direction:

http://www.elated.com/forums/authoring-and-programming/topic/new/

@akilshaikh: You need to modify the submitFinished() JS function to do the redirect. You can't spit out the JS from your PHP script like that. The contact form JS expects an Ajax response string ("success" or "error"). If you need to redirect to a dynamically-generated URL then I suggest you get your PHP script to return the URL in the Ajax response. Then modify submitFinished() to treat a response string beginning with "http://" as "success", then just do 'window.location.href=response'.

@bruceleigh: The fallback JS validation (for non-HTML5-aware browsers) only checks for non-empty fields. It doesn't validate the email address. If you want to validate an email address in JS see: http://stackoverflow.com/questions/46155/validate-email-address-in-javascript

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
23-Mar-12 05:01
duh! completely forgot about the browser validation issue - ill be off to do some coding then!

interesting disussions in that stackflow reference - many thanks
24-Mar-12 14:16
well... i think no chance for a bit support to use it in wordpress...

/sad
26-Mar-12 05:18
Hi Matt!

Thank you for this wonderful tutorial

I have a question regarding the PHP form mailer and email syntax.
I would like to also add the dot com (org, ee etc) there too because at the moment it sends the form even if I just enter m@m in the email field but it should only work when I must enter m@m.com for example.

This is the line you have

$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderEmail'] ) : "";


I have tried different options but none of them work. For example I tried this

$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9.a-z{2,3}]/", "", $_POST['senderEmail'] ) : "";


I am not a programmer but I am learning
05-Apr-12 05:33
@littlefox: Sounds like you want to validate your email address field to ensure it contains .com. ,org etc, yes? The line of code in the PHP script is for filtering, not validation.

Your best bet is probably to add some validation to the JavaScript submitForm() method - something simple like this should do it:


  // Are all the fields filled in?

  if ( !$('#senderName').val() || !$('#senderEmail').val() || !$('#message').val() || ( $('#senderEmail').val().match( /(\.[a-z]{2,4}$)/ ) ) ) {

...


This adds a regex to the validation to check that the email address ends with a dot, followed by between 2 and 4 letters.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
10-Apr-12 21:40
Hi, and thank you for the great tutorial!

I've translated this source code to Persian but I have a little problem with it!

The problem is when I write a Persian name (ex: امین) it doesn't send the email! but if I add an English word to it like "امین2" it sends the email by the name of "2"!

Can u help with this?! what is causing this?!!

Thank u again!

Regards!

[Edited by amin on 10-Apr-12 22:06]
11-Apr-12 04:29
Hello, it's the best contact form i have seen on the net. Anyway I've got a problem.
I was read almost all posts here but I didn't found my problem.

How it look's like:
After "send" if it is success you should get msg "thanks, sending etc" and on other case "fail".
In my case, after click "Send", mail is sending to recipient email, but look like my php files doesnt not send success command to ajax in html file and on screen is display second case "fail" - "There was a problem sending your message. Please try again."

Php on my server should work good and I think it is, cuz it sending email. But i have no idea where the problem is.

Here's link with your contact form on my server.


http://cactusek.home.pl/contact/index.html
12-Apr-12 06:25
hello,

First thing, great job on this tutorial!
Second thing, i dont know if its just me, but i cant seem to get recaptcha working with this form. i tried it with only the php script and it worked fine. But when javascript is beetween something goes wrong.
Is there anything i need to add to this javascript to get it working?
13-Apr-12 07:12
Ok i found out whats the problem so my post is solved.

Maybe it will helps other guys.
I've got statistics on my server which were add script on the bottom code that php could send msg back to jquery form script.

Greetings
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!
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.

Many thanks

Dave

--
DT
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 Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
27-Apr-12 18:48
@aliveit: Try turning off JavaScript in your browser then reload the page and submit the form. See what happens.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
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
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

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
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.


<!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
$('#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
return false;
}


// 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( "" );

$('#lista').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>

<!-- Some IE7 hacks and workarounds -->

<!--[if lt IE 8]>
<style>

/* IE7 needs the fields to be floated as well as the labels */

input, textarea {
float: right;
}

#formButtons {
clear: both;
}

/*
IE7 needs an ickier approach to vertical/horizontal centring with fixed positioning.
The negative margins are half the element's width/height.
*/

#contactForm.positioned, .statusMessage {
left: 50%;
top: 50%;
}

#contactForm.positioned {
margin-left: -20em;
margin-top: -16.5em;
}

.statusMessage {
margin-left: -15em;
margin-top: -1em;
}

</style>
<![endif]-->









</head>

<body>
<div id="todo">
<div id="cabecera">
<div id="logo">
<a href="#"><img alt="Kromweb" src="img/logo_kromweb.jpg" title="Kromweb" width="559" height="145" border="0" /></a>
<h1>Titulo</h1>
<h2>Diseño Gráfico | Diseño Web | Publicidad | Merchandising</h2>
</div>
<div id="contacto">
<p ><span>(+34)&nbsp;655&nbsp;59&nbsp;09&nbsp;80</span></p>
<p>&nbsp;e-mail:<a href="#contactForm">&nbsp;myname@myweb.com</a></p>
</div>
</div>




<!--LISTA-->
<div id="lista">
<ul class="miniaturas">
<li>
<a href="#">
<img class="min" src="img/chicas/1.jpg" alt="#" border="0"/>
<img class="max" src="img/grandes/1.jpg" alt="#" border="0"/>
</li>

</ul>
</div>


<!--FORMULARIO-->

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

<h2>Mándenos un correo...</h2>

<ul>

<li>
<label for="senderName">Nombre</label>
<input type="text" name="senderName" id="senderName" placeholder="Por favor, escriba su nombre" maxlength="40" required="" />
</li>

<li>
<label for="senderEmail">Correo electrónico</label>
<input type="email" name="senderEmail" id="senderEmail" placeholder="Por favor, escriba su Email" maxlength="50" pattern="^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$" required="" />
</li>

<li>
<label for="message" style="padding-top: .5em;">Mensaje</label>
<textarea name="message" id="message" placeholder="Por favor, escriba su mensaje" cols="80" rows="10" maxlength="10000" required=""></textarea>
</li>

</ul>

<div id="formButtons">
<input type="submit" id="sendMessage" name="sendMessage" value="Enviar Email" />
<input type="button" id="cancel" name="cancel" value="Cancelar" />
</div>

</form>
<div id="sendingMessage" class="statusMessage"><p>Enviando su correo. Por favor, espere...</p></div>
<div id="successMessage" class="statusMessage"><p>¡¡Gracias por enviar su mensaje!!. Le responderemos lo antes posible.</p></div>
<div id="failureMessage" class="statusMessage"><p>Ha habido un problema al enviar su mensaje. Por favor, inténtelo de nuevo.</p></div>
<div id="incompleteMessage" class="statusMessage"><p>Por favor, complete todos los campos del formulario antes de enviarlo.</p></div>


</div>
</body>
</html>

<?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, inténtelo de nuevo.</p>" ?>
<p>Pulse atrás en el navegador para volver a la página anterior.</p>
</body>
</html>
<?php
}
?>









Thank you very much.

[Edited by vassilij on 20-May-12 16:54]
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]
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]
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" );

is there other value I need to change?

I always getting fail with the php contact system
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
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.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
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
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

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
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
10-Aug-12 02:11
@mcall: See http://www.html-form-guide.com/php-form/php-form-checkbox.html

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
10-Aug-12 02:40
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
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.
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.
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 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]
13-Sep-12 15:53
Hi Matt,

I having a problem with your form since I move my web server to my own iMac. My server before was yahoo server but now i decide to host my own site using OS X Server and since i move all my file the form giving me always some of the no sending messages because it doesn't send the emails????

what could creating me this situation???

Best Regards


mbarcala
25-Sep-12 02:15
@mbarcala: Could be lots of things. You'll need to look at each step in the mail sending process to see where the problem is.

- Is the PHP script set up correctly?

- Is the PHP engine correctly configured to send mail on your server?

- Is the Mac OS X MTA (postfix) correctly configured and running?

- Does your ISP allow outgoing mail to be sent on port 25? (Many ISPs don't)

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
08-Oct-12 04:20
Hello all,
hi Matt.

For a friend of mine I’m workin on this form which really rocks (thanks so much) but I’ld like to protect it from being spam with those tiny pieces of code:

- in the form:
<input type="text" name="bot" id="spambot" />

- in the CSS:
input#spambot{visibility: hidden; display: none;}

- in processform.php:
if(!empty($_POST) && empty($_POST['spambot']))


but something is going wrong.
As I’m not a PHP expert I don’t know where in the processform.php file I have to put the php line.
If you can help it would be great.
Thanks in advance.
Thomas.

EDIT :
Found this which works great:

just add this:
- if(!strlen($_POST['spambot'])>0){

before:
if ( $senderName && $senderEmail && $message ) {


And no more spam.

[Edited by Detoussay on 12-Oct-12 08:42]
16-Oct-12 10:51
I have another question.

What will I have to change if i want to have the Form always visible?
I’s working but after having sent the email, the status message appears on a new page. The Ajax message doesn’t appear on the page itself.
28-Oct-12 05:12
Another question

Would it be possible to have the send button in javascript?
The idea behind is pretty simple:
as bots do not see javascript buttons (as far as I know) this button will be only seen by humans.

Another special button only seen byt bots will lead the to a kind of blackhole (see http://perishablepress.com/blackhole-bad-bots/ for the script).

And, tada, there we got a spamproof form (I hope)
21-Nov-12 20:51
@Detoussay: If you can post the URL of the form then we can take a look at the problem.

JavaScript-only submit buttons aren't a good idea from an accessibility point of view. Besides, a spambot can still easily "fake" a form post by just sending a POST request to the server.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
28-Nov-12 09:46
Oh, dear, it is no any defence in your script against sql injection and all site can be hacked in 1 sql line in body of request!

I am worring because I planed to use this script for
http://autoshop.kiev.ua
but now I am in doubt - is it safe or not?
30-Nov-12 11:55
it's a fantastic little heavy-less ajax script, love it, but ...
the formprocess ... good grief that needs a major rewrite, every little boy can hack and inject you with their little left finger only...

I love the whole setup but yes, ... I won't use it because of what I just addressed.

@Detoussay:
I don't know PHP at all but, if you open something... '{' then you need to close it!
Hence, you should mention to add a '}' after the one 'if' which you place your 'if' just in front of. ...

@matt:
you address Detoussay and tell him... a spammer still can ...
Well that's true, but using your form process php as it is, every spammer and all sick folk can do with you whatever they feel like.

Have you planned to come up with a secure form processing php at all?

Cheers

[Edited by hellolittlebro on 30-Nov-12 11:59]

--
Nothing isnt really something if there isnt anything.
01-Dec-12 05:56
Another thing... I added a message styling and also included the "msg" in the header, but nothing gets sent

Another thing... the current email validation isn't really a validation... sdsd@q is not an email, is it? So I changed the reg

/[^\.\-\' a-zA-Z0-9]/

to

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

but it still gets validated the old way.

Yes - I cleared cookies and even flushed the cache, tried other browsers I haven't opened it before and all the same ...

Hm... nice as it is but try to add anything, nothing!

So after all, I guess it's only for people who use it as is and don't bother about security, hijacking, etc. at all. ... perfect for the FaceBook crowd

--
Nothing isnt really something if there isnt anything.
03-Dec-12 17:45
You can't "validate" an email address until you send the message and it doesn't "bounce".

All validators of any kind do is check that the string entered has the '.'s and the '@' in the right places, and does not contain any 'illegal' characters.

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
03-Dec-12 20:38
@chris

you just proved what kind of lousy programmer you are. What are you talking about, shall I send you my code I have on another form, a form which I actually USE!
?
Gee, another "professional" (spammer, hacker, phisher >>> ??? )! Can only be one fo these, to keep your doors open you lie at other! We know how you folks work. but not everyone is as dumb as you'd hope!

[Edited by hellolittlebro on 03-Dec-12 20:40]

--
Nothing isnt really something if there isnt anything.
04-Dec-12 03:20
In that case




"Another thing... the current email validation isn't really a validation... sdsd@q is not an email, is it? "

What is the question?

Because that is the one I answered.

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
17-Dec-12 16:00
@gurkin: The tutorial isn't a lesson in how to prevent SQL injection (it doesn't even use a database). It's a tutorial showing how to use Ajax with jQuery and PHP to send an email message.

If you want to adapt the PHP script to insert data into an SQL database then you'll need to take your own precautions against injection attacks. I recommend using PDO with bound parameters.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
12-Jan-13 06:41
On your demo page the modal doesn't close when clicking the escape key - doesn't work on my page either

Any simple fix? Close outside solution would be nice too. 'Slick' form indeed otherwise.

Thx in-advance


-------------------------------

Found out how to make clicking outside the form close it.

// Close the Form when click outside
$("#subscribeForm").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$("#subscribeForm").hide(); //click came from somewhere else
$('.wrapper').fadeTo( 'slow', 1 );
});

Got it from here: http://stackoverflow.com/questions/3314810/jquery-trigger-event-when-click-outside-the-element

[Edited by freeHat on 12-Jan-13 09:55]
13-Jan-13 23:07
@freeHat: Esc key works for me! What browser are you using?

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
08-Feb-13 15:31
Excellent tutorial, works straight out of the box. Am wondering why people are asking about SQL injections considering, uhmm, the form doesn't write to a database!

Anyways my question to Matt, have no problems with the html, php, and css, but am a newbie to jquery Trying to add an additional field to the form, Phone Number, and it blows the hide and show aspects

Have simply copied the Name <li> and renamed the variables to contactPhone, increased the form height, and added a check to the js that Phone has been entered.

Quite perplexing and no doubt something very simple that I am overlooking.

Thanks in the advance for any help.
11-Feb-13 02:27
@Jeff_R: Can you post the URL of your form page with the problem?

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
16-Mar-13 11:06
Hi Matt, This is certainly a slick contact form and its exactly what Im looking for, but I keep on having an issue with the form submit. Specifically, after I fill out the form and submit, I get the error message that there was a "problem sending." However, the email actually goes through. I know some others had this same issue, but I can't find the fix for it. The code I used is identical, from what I can tell, to the one you wrote. I could use a little help.
Thanks!

Update: I did a work around. Given the emails were going through, I just tweaked the javascript. Its not the most elegant, but it sure does feel damn good to not get the error message

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
$('#successMessage').fadeIn().delay(messageDelay).fadeOut();
$('#senderName').val( "" );
$('#senderEmail').val( "" );
$('#message').val( "" );

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

[Edited by busseg on 16-Mar-13 12:05]
02-Apr-13 09:09
Hi Matt,
my hosting provider is yahoo and I having a problem receiving email using your form, is there any problem with you php file version and the 5.3.6 version?

i just don't understand why is not working now?

i having change anything from your code since i don't know much about php, but since yahoo change to 5.3.6 this problem start happening to me and i can't go back to the php version before!

any help i will appreciate please?



<?php
// Define some constants
define( "RECIPIENT_NAME", "Name Here" );
define( "RECIPIENT_EMAIL", "name@example.com" );
//define( "EMAIL_SUBJECT", "Visitor Message" );

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

$emailMessage = <<<EOD
Name: $conSenderName

$conMessage
EOD;

// If all values exist, send the email
if ( $conSenderName && $conSenderEmail && $conSenderSubject && $conMessage ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $conSenderName . " <" . RECIPIENT_EMAIL . ">" . "\r\n" . "Reply-to: " . $conSenderEmail;
$headers = "MIME-Version: 1.0rn";
$headers .= "Content-type: text/html; charset=iso-8859-1rn";
$success = mail( $recipient, $conSenderSubject, $emailMessage, $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>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>
21-Apr-13 08:42
Hello!

Can you point me how I can add to form and email body additional field Phone?

Thank yo!
29-Apr-13 23:40
@mbarcala: The PHP code looks OK (although of course you should uncomment the EMAIL_SUBJECT define at the top). What isn't working exactly?

@one: See:

http://www.elated.com/forums/topic/5171/#post21905
http://www.elated.com/forums/topic/5171/#post21909

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
28-May-13 10:23
Hi Matt,

I have 2 issues for you with your form now

1- my subject field, display all word together when i receive the email?

and 2

yours
$headers = "From: " . $senderName . " <" . $senderEmail . ">";

my
$headers = "From: " . RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">" . "\r\n" . "Reply-to: " . $conSenderEmail;


with your header i can't send any email with this form, alway give me an error message "There was a problem sending your message. Please try again."
with my i can send the email BUT i can't replay to the senderEmail, it just replay to my self.

what could be my problem? i'm using yahoo server PHP 5.3.6

hope you can help to figure out this situation

Best regards

mbarcala
28-May-13 10:24
Sorry subject field here


$conSenderSubject = isset( $_POST['conSenderSubject'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['conSenderSubject'] ) : "";
30-Jul-13 10:52
Hi, this is nice to tutorial
1)

My question is how use different language character in form filing like croatian ŠĐČĆŽ, i've been allready tried your suggestion with preg_replace /u but can't accomplish it properly.

Could you please write where to add /u into this variable:

$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";

http://croaticainfo.com

[Edited by cro2013 on 01-Aug-13 09:21]
13-Aug-13 00:12
@cro2013:


$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/u", "", $_POST['message'] ) : "";


--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
06-Jan-14 11:39
Hi Matt,

Thanks for the nice form! One thing has me puzzled, though. If I submit the form without filling in the name I get the message:

! Please fill out this field

But this is not the incompleteMessage and, in fact, this message appears before

function submitForm()

is even entered. A search through all of your files doesn't even find "Please fill out this field". So where is this message coming from? What is checking the form at this level, before submitForm() is entered?

Thanks

[Edited by toonbon on 06-Jan-14 11:53]
09-Feb-14 09:22
Hi,
I cant send the mail through contactform i got below error always

There was a problem sending your message. Please try again.

Click your browser's Back button to return to the page

. I am not change any code in processform.php. except below one

<?php

// Define some constants
define("RECIPIENT_NAME","krishna");
define("RECIPIENT_EMAIL","krishna@kirshnam.com");
define("EMAIL_SUBJECT","Visitor Message");

// Read the form values


my webpage jetnet.in
pls some one help me to fix it

Thanks
26-Feb-14 19:37
@kirshnam

you are using the wrong version of jqery, this tutorial is using jqery 1.5.1 and in your website you are using jqery 1.6.3, thats why is not working.
05-Mar-14 05:55
I have same problem that kirshnam and I use the correct version of jquery.
I have this problem when I submit the form "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
Thanks
05-Mar-14 11:18
"Origin 'null' is therefore not allowed access."

Make sure it has a value then.

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
07-Mar-14 09:19
Hi Matt, and others.

This is an awesome form and I can't wait to use it, however I'm having 1 issue.

I'll start by saying all the functions are working to send and receive the emails.

My issue is the Java Script isnt firing.

I'm using a wordpress theme.

I'm placing the script in the header.

and the <FORM> in the <BODY> . The forum shows up at the end of the body, and when the button is clicked it just instant scrolls down to the #contactForm Class.

Is there an issue with this script and wordpress?
07-Mar-14 11:48
I want to add a field to the email submit.

I'm able to create the field in the HTML markup but I can't get the field to be included in the email from the PHP

I tried replicating the $message - and changing all the variables to $phone but I wasn't able to accomplish this.

Any help would be great! Thanks!
29-Mar-14 17:35
Fistly, fantastic script, I've had fun customizing it, very smooth and brilliant.

I'd like to make the email & name optional, is there a way to do that? I tried removing the "required" aspect, and I also tried editing the php file, removing the name and email from this line:

if ( $senderName && $senderEmail && $message )

But not luck. Any suggestions?
13-May-14 12:31
This works great if you are having the contact form send to an email on the same server. I've tried this on multiple servers trying to get it to email outside the server and it doesn't work. Am I missing something or does this need additional code added to use sendmail or something similar?

[Edited by vegas on 13-May-14 12:32]
15-May-14 15:45
You need to configure sendmail to route mail via an external SMTP server, known as a 'smarthost'.

http://www.howtoforge.com/configuring-sendmail-to-act-as-a-smarthost-and-to-rewrite-from-address

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
18-May-14 03:02
hi matt,

This is a very nice Contact Form. I have everything working and giving me the correct responses on my web page. The only thing I am having a problem with is. I am not receiving the email. I tried sending it to my yahoo account and then changed it to my gmail account but it is not getting to either one nor does it show up in my spam. Do you know or have a fix for this? thanks
18-May-14 07:04
"Do you know or have a fix for this?"

No and no, will you be offering more clues so we can assist?

Such as "Where are you sending mail from"?

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
18-May-14 08:36
@butterman, did you read the reply to my post about that exact problem from chrishirst? The form is not configured to use sendmail to deliver mail outside the server. Follow the directions in the link he gave in my post above yours or you can can create an email account on the server you have the script on and have that forward to your yahoo or gmail.
18-May-14 13:25
" The form is not configured to use sendmail to deliver mail outside the server."

How do you know that??

"butterman" hasn't actually said where the script is running, it may be the same problem as you have, but then it could be one of a dozen other things that create issues with Gmail and/or Yahoo! rejecting email messages.

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
18-May-14 13:47
You're such a condescending cock sucker you know that chrishirst! You are the one that said in order to send outside the server the script is on to configure sendmail to use an external smtp.

"You need to configure sendmail to route mail via an external SMTP server, known as a 'smarthost'."

Why would your brilliant bitch ass say that if the script was really worth a **** and had the ability already built into it? It does now that I've torn it all apart and rewritten it to save to MySQL and email to any email configured into it.
You're a douchebag dude, people are asking for help not a punk with a smart ass answer like you have every time!
18-May-14 17:55
That was as an answer to a completely different question, one were the real problem was known.

Now, maybe you should go and look up the meaning of tutorial. The script isn't intended as a fully featured, "one script fits all" solution, it is for anyone learning to code to LEARN FROM and extend as necessary.

Just because the message does not arrive at Yahoo and Gmail account does not mean that it is not leaving the machine the script is.

Anyway when you have grown up enough to know that trying to insult someone you don't know is rather infantile, and a little pathetic, you might even know that ASSUMING anything is not the way to provide useful answers.

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
19-May-14 23:30
I am sending mail through godaddy and down to my gmail account. It works great when someone puts their hotmail account in and now their gmail account, It's just not coming though when they use their yahoo email account. I am not sure about outlook or any other email accounts at this time. I think the problem has to be with this SMTP stuff you are talking about so I will go school myself on that and see if I can find a fix. I think this is the best looking contact form out there so I will get it to work. When I find the fix I will let you know. In the mean time if something comes to mind. Please let me know. Thank you for your time.
20-May-14 22:27
Chris....I finely understand what you mean about route mail via an external SMTP server. I was actually trying to route the emails straight to my gmail account from the processform.php file. Everything was showing up but the yahoo emails for some reason where not. Then I created a new email name in my godaddy account and put that email name in the processform.php file. I put a forward to my gmail from my new godaddy email and everything works. I am going to assume thats what you mean by route mail via an external SMTP server, (ie... use the email name on the server not you gmail name) Thank you for the help......
21-May-14 10:35
Good, and thanks for returning and posting the steps you took to solve it, that will possibly assist future viewers of this thread.

And to vegas as it transpires your guess was correct but you STILL need to learn how to address people without using profanities and infantile insults.

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
22-May-14 10:54
I followed along with this tutorial and I must say, wow. Very insightful. Thank you so much.

I am running into one problem while trying to add a little extra functionality and I cannot seem to wrap my mind around it. If I leave everything as is, the code works great and it sends the email just fine. But what I am trying to add into the PHP page is the functionality to where, before the email is sent, it stores the variables into a MYSQL database. However, the moment I add the code below, I receive the message: "There was a problem sending your message. Please try again." If I remove the INSERT statement from the PHP page, everything goes back to running smoothly and sending the email. Here is the current code I am using to try and insert the data into the database:



<?php

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

// Read the form values
$success = false;
$senderName = isset( $_POST['senderName'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderName'] ) : "";
$senderAddress = isset( $_POST['senderAddress'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderAddress'] ) : "";
$senderCity = isset( $_POST['senderCity'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderCity'] ) : "";
$senderState = isset( $_POST['senderState'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderState'] ) : "";
$senderZip = isset( $_POST['senderZip'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderZip'] ) : "";
$senderPhone = isset( $_POST['senderPhone'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderPhone'] ) : "";
$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'] ) : "";

//set default active status
$active = '1';

//insert into database before sending response to the browser
$sql = "INSERT INTO `Quotes` (`quote_name`) VALUES ('$senderName')";
$sql_result = mysql_query($sql,$connection) or die ('Could not Insert the Quote Request');

// 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>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>


If anyone can help me with this issue, that would be incredible. Thank you so much.
22-May-14 13:03
I wanted to post again because, after much head-banging against a wall (LOL), I finally realized the errors of my way. The problem was that I was trying to insert into a database that I hadn't connected to yet. So al I had to do was actually connect to the database (what a novel idea) and all was well.

Thanks again Matt for a wonderful tutorial.
22-May-14 14:56
After getting everything to work properly, I actually do have 1 question about the difference between the example on this site and the one I implemented on my site.

When I downloaded the source codes and applied the files to my server, and tried it out, it worked great both on my desktop and on my mobile phone. On my mobile phone, the modal window fits nicely into the size of my screen. However, when I view my version that I altered a bit on my mobile phone, the modal does not shrink down, and most of the important buttons and text fields fall off the screen and makes it impossible to use. Does anybody have an idea of what would make mine differently? Here is my CSS code that I used:



/* Set default display to NONE */

#contactForm {
display: none;
overflow-y: scroll;
}

/* Add curved borders to various elements */

#contactForm, .statusMessage, input[type="submit"], input[type="button"] {
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-o-border-radius: 10px;
border-radius: 10px;
}

#contactForm, .statusMessage {
color: #666;
background-color: #fff;
background: -webkit-gradient( linear, left bottom, left top, color-stop(0,#dfe1e5), color-stop(1, #ebedf2) );
background: -moz-linear-gradient( center bottom, #dfe1e5 0%, #ebedf2 100% );
border: 1px solid #aaa;
-moz-box-shadow: 0 0 16px rgba(0, 0, 0, .5);
-webkit-box-shadow: 0 0 16px rgba(0, 0, 0, .5);
box-shadow: 0 0 16px rgba(0, 0, 0, .5);
z-index: 999;
}

/* The form dimensions */

#contactForm {
width: 640px;
height: 528px;
padding: 0 24px 24px 24px;
margin: 0 auto;
}

/* Position the form in the middle of the window (if JavaScript is enabled) */

#contactForm.positioned {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin-top: auto;
margin-bottom: auto;
}

/* Dimensions and position of the status messages */

.statusMessage {
display: none;
margin: auto;
width: 480px;
height: 32px;
padding: 24px;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}

.statusMessage p {
text-align: center;
margin: 0;
padding: 0;
}

/* The header at the top of the form */

#contactForm h2 {
font-family: nevis;
font-size: 28px;
margin: 0 5%;
padding: 16px;
width: 90%;
color: #fff;
background-color: #810d0d;
border-bottom: 1px solid #aaa;
}

/* Give form elements consistent margin, padding and line height */

#contactForm ul {
list-style: none;
margin: 0;
padding: 0;
}

#contactForm ul li {
margin: 14px 0 0 0;
padding: 0;
}

#contactForm input, #contactForm label {
line-height: 16px;
}

/* The field labels */

label {
display: block;
float: left;
clear: left;
text-align: right;
width: 28%;
padding: 6px 0 0 0;
margin: 2px 8px 0 0;
font-family: nevis;
font-weight: bold;
}

/* The fields */

input, textarea {
display: block;
margin: 0;
padding: 6px;
width: 67%;
font-family: "Georgia", serif;
font-size: 16px;
border: 1px solid #aaa;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
-webkit-box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
background: #fff;
}

textarea {
height: 208px;
line-height: 24px;
resize: none;
}

/* Place a border around focused fields, and hide the inner shadow */

#contactForm *:focus {
border: 1px solid #66f;
outline: none;
box-shadow: none;
-moz-box-shadow: none;
-webkit-box-shadow: none;
}

/* Display correctly filled-in fields with a green background */

input:valid, textarea:valid {
background: #dfd;
}

/* The Send and Cancel buttons */

input[type="submit"], input[type="button"] {
float: right;
margin: 32px 16px 0 16px;
width: 160px;
padding: 8px;
border: 1px solid #666;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
-moz-box-shadow: 0 0 8px rgba(0, 0, 0, .8);
-webkit-box-shadow: 0 0 .8px rgba(0, 0, 0, .8);
box-shadow: 0 0 8px rgba(0, 0, 0, .8);
color: #fff;
background: #0a0;
font-size: 16px;
line-height: 16px;
font-weight: bold;
opacity: .7;
-webkit-appearance: none;
-moz-transition: opacity .5s;
-webkit-transition: opacity .5s;
-o-transition: opacity .5s;
transition: opacity .5s;
}

input[type="submit"]:hover,
input[type="submit"]:active,
input[type="button"]:hover,
input[type="button"]:active {
cursor: pointer;
opacity: 1;
}

input[type="submit"]:active, input[type="button"]:active {
color: #333;
background: #eee;
-moz-box-shadow: 0 0 8px rgba(0, 0, 0, .8) inset;
-webkit-box-shadow: 0 0 8px rgba(0, 0, 0, .8) inset;
box-shadow: 0 0 8px rgba(0, 0, 0, .8) inset;
}

input[type="button"] {
background: #f33;
}

.modal-red-star {
font-family: nevis;
font-size: 24px;
font-weight: bold;
color: #810d0d;
padding-top: 6px;
}


Any help on this issue would be greatly appreciated.
23-Jun-14 10:24
I'm implementing this form into my site as we speak because without doubt, it is unbelievably slick! BUT one problem I've been trying to sort out, can anyone figure out why theres a big blank space in the message text area and it'll only display the placeholder image after deleting some whitespace? thanks

my site is at http://joewinfield.net/portfolio
24-Jun-14 04:27
A textarea element will display everything that is between the start and end tags, so if your source code has a line break in the tag structure, ... So will the rendered document.

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
25-Jun-14 06:07
Chrishirst you're right! i accidentally left in whitespace when cleaning up how my code was laid out. the smallest things always catch you, thanks
27-Jun-14 12:18
I know you're showing how to make a contact form appear so it's non-obstrusive on a page, but if I just wanted to load the contact form so it appears within a page(without onclick) and still functional, how can it be done?
28-Jun-14 12:17
Make it visible by default rather than requiring the mouse click.

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
09-Jul-14 03:45
Hi Matt, still using this great script but I've recently been hit (big time) by spambots.

Rather than mess around with captchas I added a line of code to capture the spammer/bot's IP address and include this in the email I receive from the form, then I add that IP address to a blacklist I use to filter out unwelcome guests and redirect them to somewhere else.

In case this helps anyone else I thought I'd share:

1) Add the following line to processForm.php, at the end of the section near the top which says "// Read the form values"

$message .= "\n" . $_SERVER["REMOTE_ADDR"];

2) Add the following script to the top of the page containing your contact form:

// blacklist spammers

$deny = array("123.242.153.113", "123.242.153.*", "95.67.80.*", "27.153.163.223", "27.153.163.*"); // remember no comma after last one
if (in_array ($_SERVER['REMOTE_ADDR'], $deny)) {
header("location: http://www.example.com/");
exit();
}

There are a couple of examples there to show how I do it - I add the offending IP address AND I also use a wildcard "*" to block any similar IP addresses.

You can redirect the spammer to another address - on a company site I take care of I actually redirect them to our company Facebook page instead.
13-Jul-14 03:31
I entered all the code but when i tried it, it just gave me the "Please complete all the fields in the form before sending." message and all the fields were filled in. desperate for help
13-Jul-14 18:31
Without seeing YOUR code, were not going to be able to provide any.

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
19-Sep-14 08:42
Helo house please am having "There was a problem sending your message. Please try again." error and all the fields are complete. please help its urgent
19-Sep-14 10:01
read the reply above yours and below the one asking EXACTLY the same question.

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
19-Sep-14 11:48
I have two questions. First is there a fix the yahoo mailing problem. I have my mail which is hosted on godaddy.com forward my mail to my gmail. If the sender post their email account with a domain of @gmail and @hotmail it gets forwarded to my mail wit no problems, but if the sender post with @yahoo domain I don't receive anything.

Second question: i'm trying to add the css on to an external stylesheet like I do for all css, but for some reason the css only works when it is embedded in the main html page. Am I missing something?

Please help me out
19-Sep-14 12:12
"Am I missing something?"

Probably.


"but if the sender post with @yahoo domain I don't receive anything."

You probably need to ask Godaddy support about that.

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/
19-Sep-14 12:26
Is there anyway to send the emails directly to my email rather than fowarding it i.e. to an email outside the server which it is hosted in?

And I figured out the external stylesheet problem, had to back out of the directory with ../
19-Sep-14 16:21
"Is there anyway to send the emails directly to my email rather than fowarding it i.e. to an email outside the server which it is hosted in? "

Again that has to be a no idea.

Does your server have a MTA installed on it?

--
Chris.
So long, and thanks for all the fish.
http://webmaster-talk.eu/

 
New posts
Old posts

Follow Elated