Contact form comes on first priority for any organisation as this may led to establish one to one communication with their customers.
Here in this tutorial, we make you learn how to create simple contact form and applying validation over it using jQuery and PHP.
We have created a simple HTML form with four fields- Name, Email, Contact No., and Message.
we used following PHP mail() function with four parameters to send email as follows:
mail("$to", $subject, $message, $headers);
- Here, $to variable is to store reciever’s email id.
- $subject is a variable to store mail subject.
- $message is a variable to store user’s message.
- $headers contains other email parameters like BCc, Cc etc.
You can download our zip file or simply follow our code and edit it to use.
-:See Also:-
HTML File: contact_form.html
Given below our complete HTML code , copy to use it.
<html>
<head>
<title>Simple jQuery Contact Form With Validation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="css/contact_form.css" />
<script src="contact_form.js"></script>
</head>
<body>
<div id="mainform">
<h2>Simple jQuery Contact Form With Validation</h2>
<!-- Required Div Starts Here -->
<form id="form">
<h3>Contact Form</h3>
<p id="returnmessage"></p>
<label>Name: <span>*</span></label>
<input type="text" id="name" placeholder="Name"/>
<label>Email: <span>*</span></label>
<input type="text" id="email" placeholder="Email"/>
<label>Contact No: <span>*</span></label>
<input type="text" id="contact" placeholder="10 digit Mobile no."/>
<label>Message:</label>
<textarea id="message" placeholder="Message......."></textarea>
<input type="button" id="submit" value="Send Message"/>
</form>
</div>
</body>
</html>
jQuery File: contact_form.js
Given below our complete jQuery code.
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var contact = $("#contact").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (name == '' || email == '' || contact == '') {
alert("Please Fill Required Fields");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("contact_form.php", {
name1: name,
email1: email,
message1: message,
contact1: contact
}, function(data) {
$("#returnmessage").append(data); // Append returned message to message paragraph.
if (data == "Your Query has been received, We will contact you soon.") {
$("#form")[0].reset(); // To reset form fields on success.
}
});
}
});
});
PHP Script: contact_form.php
Below script executes for Validating and to send Email.
<?php
// Fetching Values from URL.
$name = $_POST['name1'];
$email = $_POST['email1'];
$message = $_POST['message1'];
$contact = $_POST['contact1'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing E-mail.
// After sanitization Validation is performed
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (!preg_match("/^[0-9]{10}$/", $contact)) {
echo "<span>* Please Fill Valid Contact No. *</span>";
} else {
$subject = $name;
// To send HTML mail, the Content-type header must be set.
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
$headers .= 'From:' . $email. "rn"; // Sender's Email
$headers .= 'Cc:' . $email. "rn"; // Carbon copy to Sender
$template = '<div style="padding:50px; color:white;">Hello ' . $name . ',<br/>'
. '<br/>Thank you...! For Contacting Us.<br/><br/>'
. 'Name:' . $name . '<br/>'
. 'Email:' . $email . '<br/>'
. 'Contact No:' . $contact . '<br/>'
. 'Message:' . $message . '<br/><br/>'
. 'This is a Contact Confirmation mail.'
. '<br/>'
. 'We Will contact You as soon as possible .</div>';
$sendmessage = "<div style="background-color:#7E7E7E; color:white;">" . $template . "</div>";
// Message lines should not exceed 70 characters (PHP rule), so wrap it.
$sendmessage = wordwrap($sendmessage, 70);
// Send mail by PHP Mail Function.
mail("[email protected]", $subject, $sendmessage, $headers);
echo "Your Query has been received, We will contact you soon.";
}
} else {
echo "<span>* invalid email *</span>";
}
?>
CSS File: contact_form.css
Styling HTML Elements.
@import url(http://fonts.googleapis.com/css?family=Fauna+One|Muli);
#mainform{
width:960px;
margin:20px auto;
padding-top:20px;
font-family: 'Fauna One', serif;
}
#form{
border-radius:2px;
padding:20px 30px;
box-shadow:0 0 15px;
font-size:14px;
font-weight:bold;
width:350px;
margin:20px 250px 0 35px;
float:left;
}
h3{
text-align:center;
font-size:20px;
}
input{
width:100%;
height:35px;
margin-top:5px;
border:1px solid #999;
border-radius:3px;
padding:5px;
}
input[type=button]{
background-color:#123456;
border:1px solid white;
font-family: 'Fauna One', serif;
font-Weight:bold;
font-size:18px;
color:white;
}
textarea{
width:100%;
height:80px;
margin-top:5px;
border-radius:3px;
padding:5px;
resize:none;
}
span{
color:red
}
#note{
color:black;
font-Weight:400;
}
#returnmessage{
font-size:14px;
color:green;
text-align:center;
}
Conclusion:
This was all about to create simple contact form with validation. Hope you like it, Keep reading our other blogs.
67 Replies to “Simple jQuery Contact Form with Validation”
Can you please tell me how to remove the require field from the contact no line.
Thanks
You need to do the changes here
if (name == ” || email == ” || contact == ”) {
change it to
if (name == ” || email == ”) {
Regards,
FormGet Team.
Hello,
You might need to clear the form once it is sent and confirmed
Thanks.
Hi,
Is there a way to remove the Contact Tel NO. as I do not wish to ask for that.
Many thanks
Hello Mario,
You need to remove all these lines from the above code :
1. <label>Contact No: <span>*</span></label>
<input type=”text” id=”contact” placeholder=”10 digit Mobile no.”/>
2. var contact = $(“#contact”).val();
3. || contact == ”
4. contact1: contact
5. $contact = $_POST[‘contact1’];
6. . ‘Contact No:’ . $contact . ‘
‘
for removing contact field and it’s working from the code.
I removed all you mentioned above (to removed the phone number column);
The column is now removed from the layout, but after filling out the form, I still get an error message, “Please Fill Valid Contact No.”
Even though there is no Contact No. field.
Hello,
can you please help me please I need to submit form data in email.
Is it possible can we submit data without php code . with jquery/ javascript?
No….Jquery/JavaScript will run at browser not in the server.And php code will run at server not in the browser.
I remove as instructed but still get error * Please Fill Valid Contact No. *
how to remove this validation from php file?
if (!preg_match(“/^[0-9]{10}$/”, $contact)) {
echo “* Please Fill Valid Contact No. *”;
} else {
hi how are you?
Hello Ganesh,
Fine thanks !
Regards,
FormGet Team.
Please, how i change the error mensage?
Thanks
Hello Vitor,
In javascript code from here :
if (name == ” || email == ” || contact == ”) {
alert(“Please Fill Required Fields”);
}
Change “Please Fill Required Fields” to your message.
and in php code from here :
{
echo “* invalid email *“;
}
Hope that will help you to solve your issue.
Thanks & Regards,
FormGet Team.
i am planing to use this script on our website.
Thanks for reading up the post.
You can implement the code where you wish to use it.
Keep reading our other blog posts for getting more knowledge and coding tricks.
Regards,
FormGet Team.
I get an alert box saying “please fill required fields” even though i fill all the fields. Can you please help me with that? Thanks.
In your php file for the email. How can I add a image LOGO
Akamerc,
This is a matter of adding the proper HTML code for an image as you would for any HTML page (). Styling and positioning is a totally different topic.
actually i have already html contact page but i want to send a mail from html contact page using php message sent to my gmail please send me link to my mail id [email protected]
When I hit submit it doesn’t come back
Hi, I have been trying to learn about .php and jQuery. I have used your code but tried to manipulate it to make a contact form. Now the submit function isnt working. This is my code:
HTML:
Contact Form
Form 1:Trainee Contact Details
Trainee’s Details.
Forename: *
Surname: *
Male/female: *
Age: *
Date of birth: *
Address;Street: *
Town: *
County: *
Country: *
Mobile: *
Email: *
Emergency contacts
Please give details of 2 people ashore who can be contacted in the event of an emergency:
Contact Name 1:
Forename: *
Surname: *
Relationship to Trainee:(mother, brother, aunt etc.) *
Phone day: *
Phone evening: *
Mobile: *
E-mail: *
Contact Name 2:
Forename: *
Surname: *
Relationship to Trainee:(mother, brother, aunt etc.) *
Phone day: *
Phone evening: *
Mobile: *
E-mail: *
PHP
<?php
//Fetching Values from URL
$forename = $_POST['forename1'];
$surname = $_POST['surname1'];
$gender = $_POST['gender1'];
$age = $_POST['age1'];
$dob = $_POST['dob1'];
$street = $_POST['street1'];
$town = $_POST['town1'];
$county = $_POST['county1'];
$country = $_POST['country1'];
$number = $_POST['number1'];
$email = $_POST['email1'];
$forename1 = $_POST['forename2'];
$surname1 = $_POST['surname2'];
$rel = $_POST['rel1'];
$phone = $_POST['phone1'];
$phone1 = $_POST['phone2'];
$mobile1 = $_POST['mobile2'];
$email1 = $_POST['email2'];
$forename2 = $_POST['forename3'];
$surname2 = $_POST['surname3'];
$rel1 = $_POST['rel2'];
$phone2 = $_POST['phone3'];
$phone3 = $_POST['phone4'];
$mobile2 = $_POST['mobile3'];
$email2 = $_POST['email3'];
//sanitizing email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
//After sanitization Validation is performed
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (!preg_match("/^[0-9]{10}$/", $number)) {
echo "* Please Fill Valid Contact No. *”;
} else {
$subject = $forename;
// To send HTML mail, the Content-type header must be set
$headers = ‘MIME-Version: 1.0’ . “rn”;
$headers .= ‘Content-type: text/html; charset=iso-8859-1’ . “rn”;
$headers .= ‘From:’ . $email. “rn”; // Sender’s Email
$headers .= ‘Cc:’ . $email. “rn”; // Carbon copy to Sender
$template = ‘Hello ‘ . $name . ‘,’
. ‘Thank you For submitting your details.’
“First Name: “. $forename . ”
“Last Name: “. $surname . ”
“Gender: “. $gender . ”
“Age: “. $age . ”
“DOB: “. $DOB . ”
“Street: “. $street . ”
“Town: “. $town . ”
“County: “. $county . ”
“Country: “. $country . ”
“Mobile: “. $number . ”
“Email: “. $email . ”””
“Contact Name 1: “. $forename1 . ”
“Contact Surname 1: “. $surname1 . ”
“Realtionship: “. $rel . ”
“Day Phone: “. $phone . ”
“Evening Phone: “. $phone1 . ”
“Mobile: “. $mobile1 . ”
“Email: “. $email1 . ”””
“Contact Name 1: “. $forename2 . ”
“Contact Surname 1: “. $surname2 . ”
“Realtionship: “. $rel1 . ”
“Day Phone: “. $phone2 . ”
“Evening Phone: “. $phone3 . ”
“Mobile: “. $mobile2 . ”
“Email: “. $email2 . ””
. ‘This is a Contact Confirmation mail.’
. ”
. ‘We Will contact you as soon as possible .’;
$sendmessage = “” . $template . “”;
// message lines should not exceed 70 characters (PHP rule), so wrap it
$sendmessage = wordwrap($sendmessage, 70);
// Send mail by PHP Mail Function
mail(“[email protected]”, $subject, $sendmessage, $headers);
echo “Your details have been received, We will contact you soon.”;
}
} else {
echo “* invalid email *”;
}
?>
JAVASCRIPT
$(document).ready(function(){
$(“#submit”).click(function(){
var forename = $(“#forename”).val();
var surname = $(“#surname”).val();
var gender = $(“#gender”).val();
var age = $(“#age”).val();
var dob = $(“#dob”).val();
var street = $(“#street”).val();
var town = $(“#town”).val();
var county = $(“#county”).val();
var country = $(“#country”).val();
var number = $(“#number”).val();
var email = $(“#email”).val();
var forename1 = $(“#forename1”).val();
var surname1 = $(“#surname1”).val();
var rel = $(“#rel”).val();
var phone = $(“#phone”).val();
var phone1 = $(“#phone1”).val();
var mobile1 = $(“#mobile1”).val();
var email1 = $(“#email1”).val();
var forename2 = $(“#forename2”).val();
var surname2 = $(“#surname2”).val();
var rel1 = $(“#rel1”).val();
var phone2 = $(“#phone2”).val();
var phone3 = $(“#phone3”).val();
var mobile2 = $(“#mobile2”).val();
var email2 = $(“#email2”).val();
$(“#returnmessage”).empty(); //To empty previous error/success message.
//checking for blank fields
if(forename==”||surname==”||gender==”age==”dob==”street==”town==”county==”country==”number==”email==”forename1==”surname1==”rel==”phone==”phone1==”mobile1==”email1==”forename2==”surname2==”rel1==”phone2==”phone3==”mobile2==”email2==”){
alert(“Please Fill Required Fields”);
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post(“contact_form.php”,{
forename1: forename,
surname1: surname,
gender1: gender,
age1: age,
dob1: dob,
street1: street,
town1: town,
county1: county,
country1: country,
number1: number,
email1: email,
forename2: forename,
surname2: surname,
rel1: rel,
phone1: phone,
phone2: phone1,
mobile2: mobile1,
email2: email1,
forename3: forename2,
surname3: surname2,
rel2: rel1,
phone3: phone2,
phone4: phone3,
mobile3: mobile2,
email3: email2
}, function(data) {
$(“#returnmessage”).append(data);//Append returned message to message paragraph
if(data==”Your details have been received, We will contact you soon.”){
$(“#form”)[0].reset();//To reset form fields on success
}
});
}
});
});
Can you tell me where I went wrong??
I have downloaded script and tried using free hosting website but it does not send the mail.
I have changed the the given mail id (“[email protected]”) with my own mail id.
Plz help me sir..
where is the database connectivity ? i mean when we enter name, message , contact where it will go and how to make connectivity in html with any database either access, sql, etc. plzz help how to make backhand coding for submit button.
Hello, I customized the form codes above to the following, but I can’t seem to get it to work. Can you please assist? Code:
JS:
$(function() {
$(“#submit”).click(function(e) {
var fname = $(“#fname”).val();
var lfame = $(“#lname”).val();
var phone = $(“#phone”).val();
var email = $(“#email”).val();
var how = $(“#how”).val();
var inquiry = $(“#inquiry”).val();
$(“#returnmessage”).empty(); // To empty previous error/success message.
// Checking for blank fields
if (fname == ” || lname == ” || email == ” || inquiry == ”) {
alert(“Please Fill Required Fields”);
e.preventDefault();
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post(“process.php”, {
fname1: fname,
lname1: lname,
phone1: phone,
email1: email,
how1: how,
inquiry1: inquiry
}, function(data) {
$(“#returnmessage”).append(data); // Append returned message to message paragraph.
if (data == “Your Query has been received, We will contact you soon.”) {
$(“#inquiryForm”)[0].reset(); // To reset form fields on success.
}
});
e.preventDefault();
}
});
});
PHP:
<?php
/* Set e-mail recipient */
$myemail = "[email protected], [email protected], [email protected]";
$subject = "Ism Clothing Contact Form Submission";
// Fetching Values from URL.
$fname = $_POST['fname1'];
$lname = $_POST['lname1'];
$phone = $_POST['phone1'];
$how = $_POST['how1'];
$inquiry = $_POST['inquiry1'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing E-mail.
// After sanitization Validation is performed
/* Validate required fields*/
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (!preg_match("/^[a-zA-Z ]*$/",$fname) || !preg_match("/^[a-zA-Z ]*$/",$lname)) {
echo "Only letters and white space allowed”;
} else {
/* Format form data for email */
$message = “Hello!
Ism Clothing contact form has been submitted by:
Name: $fname $lname
E-mail: $email
Phone #: $phone
How did he/she find it? $how
Comments:
$inquiry
End of message
“;
/* Send the message using mail() function */
mail($myemail, $subject, $message);
echo “Your Query has been received, We will contact you soon.”;
}
} else {
echo “Invalid Email”;
}
?>
Hi,
Please give me some details.
can you let me know how this comment section coding is happening
Sir,
I want to add a calender field. How it is possible. Tell me how can i fetch the data to PHP.
Thank you.
how to link php file in html
im not rcving any email why?
Hi there!
I’ve just used your code on my website using Dreamweaver (great form by the way). I’ve followed as per your instructions above. It looks great when I preview it, however when I click on Send message, nothing seems to be happening! The only thing I have changed is the recipient email which is obviously my email.
Any idea what the problem could be?
Look forward to hearing from you!
Thanks,
Devki
Great script! I improved it a little bit so it’s more personalized to each party:
contact_form.php:
<?php
// Fetching Values from URL.
$name = $_POST['name1'];
$email = $_POST['email1'];
$message = $_POST['message1'];
$contact = $_POST['contact1'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing E-mail.
// After sanitization Validation is performed
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (!preg_match("/^[0-9]{10}$/", $contact)) {
echo "Please put in a valid phone number (no dashes)”;
} else {
$subjectCust = ‘Thank you for your message ‘.$name;
$subjectOwner = ‘Website message from: ‘ . $name;
// To send HTML mail, the Content-type header must be set.
$headers = ‘MIME-Version: 1.0’ . “\r\n”;
$headers .= ‘Content-type: text/html; charset=iso-8859-1’ . “\r\n”;
$headers .= ‘From:’ . $email. “\r\n”; // Sender’s Email
$template2Customer = ‘Hello ‘ . $name . ‘,’
. ‘Thank you for contacting us.’
. ‘Your message to us: ‘
. ‘Name:’ . $name . ”
. ‘Email:’ . $email . ”
. ‘Contact No:’ . $contact . ”
. ‘Message:’ . $message . ”
. ‘This is a confirmation mail.’
. ”
. ‘We will contact you as soon as possible.’
. ‘http://www.YOURWEBSITE.com’;
$template2SiteOwner = ‘Website message from: ‘
. ‘Name: ‘ . $name . ”
. ‘Email: ‘ . $email . ”
. ‘Contact No: ‘ . $contact . ”
. ‘Message: ‘ . $message . ”
. ”
. ‘This message was sent from: http://www.YOURWEBSITE.com‘;
$sendmessage2Cust = $template2Customer;
$sendmessage2SiteOwner = $template2SiteOwner;
// Message lines should not exceed 70 characters (PHP rule), so wrap it.
$sendmessage2Cust = wordwrap($sendmessage2Cust, 70);
$sendmessage2SiteOwner = wordwrap($sendmessage2SiteOwner, 70);
// Send mail by PHP Mail Function.
mail($email, $subjectCust, $sendmessage2Cust, $headers);
mail(“[email protected]”, $subjectOwner, $sendmessage2SiteOwner, $headers);
echo “Your message has been received, we will contact you soon.”;
}
} else {
echo “* invalid email *”;
}
?>
Thank you for sharing your optimization Emil G. It worked, except the formatting was missing line breaks… working through it now.
It was all coming out in one single line; I had to use double quotes with \n for line breaks.
Hi,
I have used this code it worked properly . I am facing one problem all message found in my spam. Why message didn’t show the inbox. plz help me. I can’t solve this issue..
Thanks
Hi, thanks for this great script! There’s a good 2 to 5 second delay between clicking submit and a success message…is there any way to either speed up that process and/or add a loader.gif in between that eventually gets replaced by the success message?
Thanks sir i got solution it is very very help full for me
thaks again
Works fine for me.
Thank you!
Great contact form ever.
It’s working for me.
Thank you
i have an error in SMTP. can u please help me?
what is exactly error of smtp in php
You rock thank you for this tool. I just replaced an old CGI/perl script and this is som much better!!
Thanks for the form source code.
i need jquery validation
I have created this and it works fine, however i have a HTML file that i wish the user to be navigated to once the form has been submitted.
The echo part is where the message is displayed, how do i tell this to navigate to my HTML instead?
Dude you rock!
Thank you so much saved me hours days weeks
I’m trying to test this form on my server before I use it on a website but I can’t get it to work.
Firstly
I don’t want the contact number to be mandatory since, when I fill the form out with correct details including my mobile number I get an alert message saying “Please enter a valid phone number” which is wrong since I am entering a valid number.
I tried this:
if (name == ” || email == ”) {
But then nothing happened when I clicked submit.
Secondly where do I put my email address as the recipient?
I’ve tried changing”[email protected]” to be my email address but this didn’t work either.
Please help.
Thanks.
Marc
when form submit not form field reset .all field is already old data show pease help
I’m curious to find out what blog platform
you happen to be using? I’m experiencing some minor security problems with my latest site and I’d like
to find something more secure. Do you have any recommendations?
Hi,
Thanks for this script. I am having a weird issue though. It works when I enter a gmail address and my work address, but does not deliver anything when I enter my Yahoo address. Any idea why that might be happening?
Thanks in advance.
Dave
Yahoo servers a very slow.. it’s normal for it to take 15-30 mins to receive email.
Perfect Script works instantly… Thanks for sharing 🙂
I’ve just used your code on my website using Dreamweaver (great form by the way). I’ve followed as per your instructions above. It looks great when I preview it, however when I click on Send message, nothing seems to be happening! The only thing I have changed is the recipient email which is obviously my email.
Any idea what the problem could be?
@Thameem – I’m also using Dreamweaver and also had the same issue you’re having. Nothing it’s happening because of the single quotes, change them to double quotes and it should work.
how to make validation or remove in text field that type in put (xyz )
hi team
i am not getting email to my id but contact form says Your Query has been received, We will contact you soon.
help me
thanks and regards
What’s up colleagues, its fantastic piece of writing concerning educationand fully explained,
keep it up all the time.
Hi there,
I have downloaded script and tried using my hosting server but when clicking the Send Message button look like it’s disabled.
Would you please let me know how to make the button work?
Hi! I have a problem with encoding messages.
I use windows-1251 and if user input cyrillic data in one of the fields (name or message), in the incoming message it isn’t displayed correctly.
I’m sure that all documents have windows-1251 encoding.
I use this in headers in contact_form.php:
$headers .= ‘Content-type: text/html; charset=windows-1251’ . “\r\n”;
And I use this in meta tag in my html document:
How can I fix it?
how to change email address in contact .php.
Wow Thank you so much you sol my big problem thanks once again
Why does the php section of this form need to be in its own file? normally I thought php was additional markup within the index file. However, when I add this to my site it only works if I have a file “contact_form.php” in my root folder. It works, but I don’t see where in the code it’s looking for this file.
thank you so much you have helped me big time
Can i plz help me email id get form name.
How can we receive two different confirmation messages ? One for webmaster, and one for client ?
Thanks
how it works on cpanel
Hi there, thanks for this !
Weird problem, when I submit the form, Jquery script returns the error “please fill Required Fields”.
So I troubleshooted the error message using this :
if (name == ” || email == ” || contact == ”) {
var msg = ‘name:’ + name + ‘ email:’ + email + ‘ message:’ + message;
alert(msg);
}
which returns the proper values (the fields were not blank).
Any help welcome.
My bad: was checking message V.S contact.
Changed the code accordingly.
if (name == ” || email == ” || message == ”) {
alert(“Merci de remplir tous les champs marqués d’une (*)”);
}
Thanks again.