Quantcast
Viewing all articles
Browse latest Browse all 13

How To Create A Simple Contact Form With AJAX and PHP

Contact forms are a great and simple way to show others how they can contact you without having to directly open up their email client and send you an email directly. In this tutorial, I’ll be going over how to create a very simple contact form (that you can use on your own website) and have it use AJAX to run a PHP file which will send you an email with that user’s contact information and load a thank you message, all without reloading the page.

I’ll be going over a few different files that we’ll be using to create the simple contact form. I’ll be using jQuery for the Ajax function and PHP to do the sending of the email content to make the contact form work correctly.

Here’s a list of all the files I’ll be going over with:

  • contact.html
  • contact.css
  • contact.php
  • contact.js

First things first… Let’s create the HTML structure. We’ll name this file contact.html.

HTML

[HTML]

< !DOCTYPE html>





Get In Touch

Feel free to contact me about anything.








[/HTML]

You’ll notice that I only have three fields where the user can enter their information at. There’s two input text fields for the user’s full name and email. Then there’s also a textarea field for the actual message that they write to you.

Next let’s make it a little fancy with some CSS. Let’s name this following file as contact.css .

CSS

[CSS]
/*————— BASE CSS STYLES ————–*/
* {
margin:0;
padding:0;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}

body {
font-size: 100%;
font-family: ‘Open Sans’,’Helvetica Neue’, sans-serif;
}
input[type=”text”],
textarea {
padding: 5px 10px;
height: 36px;
border: 1px solid #ccc;
font-size: 1em;
font-family: ‘Open Sans’,’Helvetica Neue’, sans-serif;
background: #fff;
margin: 0 0 10px;
width: 100%;
display: block;
}
textarea {
min-height: 100px;
}
.hidden {
display: none;
}

/*———– PAGE STYLING ———-*/

.contactWrap{
width: 1000px;
margin: 40px auto;
}
.contactWrap h2,
.contactWrap p {
margin: 0 0 5px;
}
.contactWrap p.error {
padding: 5px;
background: #d7a4a4;
}

input.required,
textarea.required {
border: 2px solid #d7a4a4;
}

.btn {
padding: 10px 1.5%;
cursor: pointer;
color: #FFFFFF;
font-size: 120%;
font-weight: bold;
text-align: center;
border: 1px solid #333333;
box-shadow: 0 1px 1px #DAEAFA inset;
background: #549ce7; /* fallback color */
background: -webkit-linear-gradient(top , #81B6ED, #2782E1 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);
background: -moz-linear-gradient(top , #81B6ED, #2782E1 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);
background: -ms-linear-gradient(top , #81B6ED, #2782E1 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);
background: -o-linear-gradient(top , #81B6ED, #2782E1 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);
background: linear-gradient(top , #81B6ED, #2782E1 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
-ms-border-radius: 4px;
-o-border-radius: 4px;
border-radius: 4px;
}
.btn:hover {
background: none repeat scroll 0 0 #3E8FE4;
}

[/CSS]

Now that we got the look and styling of the contact form out of the way, let’s start the actual logic to create the contact form. Let’s name this file contact.php .

PHP

[PHP]
< ?php

//This is the email address that the contact form will be send to. Usually this will be your email address
$to = "email@mywebsite.com";

//This is so you know what the email subject is about
$subject = "From My Website Contact Form";

//Name of the person who emailed you.
$name_field = $_POST['name'];

//Email of person
$email_field = $_POST['email'];

//this is what the person wants to tell you!
$message = $_POST['message'];

//combine everything to the body of the email
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message\n";

//send the email
mail($to, $subject, $body);

?>
[/PHP]

All we’re doing in this PHP file is grabbing all the values from the form fields and sending them to an email address. Then it spits out a thank you message.

You’ll notice that in the first part we set a $to and $subject variables which we will need to send out our email. Then we grab the values from the input fields using $_POST and apply them to the $name_field, $email_field, and $message variables. Then we combine all three of those variables into the body of the email and then send the email out.

Note: This PHP script is a very, very simple email script and may not work properly on some servers. Please contact your server support if you get errors.

Now that we got that out of the way, the last file we’ll add is the contact.js file which will tie all the pieces together and run the AJAX request.

JavaScript/jQuery

[JAVASCRIPT]
$(document).ready(function(){

//validation contact form
$(‘#submit’).click(function(event){
event.preventDefault();

var fname = $(‘#name’).val();
var validInput = new RegExp(/^[a-zA-Z0-9\s]+$/);
var email = $(‘#email’).val();
var validEmail = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
var message = $(‘#message’).val();

if(fname==”){ showError(‘Please enter your name.’, $(‘#name’)); $(‘#name’).addClass(‘required’); return;}
if(!validInput.test(fname)){ showError(‘Please enter a valid name.’, $(‘#name’)); $(‘#name’).addClass(‘required’); return;}
if(email==”){ showError(‘Please enter an email address.’, $(‘#email’)); $(‘#email’).addClass(‘required’); return;}
if(!validEmail.test(email)){ showError(‘Please enter a valid email.’, $(‘#email’)); $(‘#email’).addClass(‘required’); return;}
if(message==”){ showError(‘Please enter a message.’, $(‘#message’)); $(‘#message’).addClass(‘required’); return;}

// setup some local variables
var request;
var form = $(this).closest(‘form’);

// serialize the data in the form
var serializedData = form.serialize();

// fire off the request to /contact.php
request = $.ajax({
url: “contact.php”,
type: “post”,
data: serializedData
});

// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
$(‘.contactWrap’).html(‘

Get In Touch

Thank you! Your message has been sent.

‘);
});

// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error( “The following error occured: “+ textStatus, errorThrown );
$(‘.contactWrap’).html(‘

Oh no!An Error occurred.

‘);
});

});

//remove ‘required’ class and hide error
$(‘input, textarea’).keyup( function(event){
if($(this).hasClass(‘required’)){
$(this).removeClass(‘required’);
$(‘.error’).hide();
}
});

// show error
showError = function (error, target){
$(‘.error’).removeClass(‘hidden’).show().html(error);
$(‘.error’).data(‘target’, target);
$(target).focus();
console.log(target);
console.log(error);
return;
}

});
[/JAVASCRIPT]

You’ll notice in the JavaScript that we do some validation of the form inputs using Regular Expressions. This is to make sure that the user enters in valid characters for their name and email. If there’s an error (such as an invalid email or a text input left blank) then it will display the error at the top of the contact form and highlight the input field in question.

If everything is valid, it will do an Ajax call to the contact.php file. From there the contact.php file will send out the email.

Then, if it’s successful we’ll replace the contents inside the .contentWrap div to tell the user that the message has been sent. If it fails, we’ll just log an error.

Conclusion

As you can see, it’s quite easy to create a simple contact form that you can use on your website for others to contact you with. Of course there are a lot more things you could add to this script, but this will give you a better idea of how to apply it to your website.

You can download the files here: how-to-create-a-simple-contact-form-with-ajax-and-php.zip

Let me know in the comments below if you found this useful or if you have any suggestions.


Viewing all articles
Browse latest Browse all 13

Trending Articles