Skip to content

Instantly share code, notes, and snippets.

@ajtroxell
Last active April 11, 2023 13:53
Show Gist options
  • Star 71 You must be signed in to star a gist
  • Fork 52 You must be signed in to fork a gist
  • Save ajtroxell/6731408 to your computer and use it in GitHub Desktop.
Save ajtroxell/6731408 to your computer and use it in GitHub Desktop.
Build a simple PHP, jQuery, and AJAX Powered Contact Form, from: http://ajtroxell.com/build-a-simple-php-jquery-and-ajax-powered-contact-form/
<form id="contact" name="contact" method="post">
<fieldset>
<label for="name" id="name">Name<span class="required">*</span></label>
<input type="text" name="name" id="name" size="30" value="" required/>
<label for="email" id="email">Email<span class="required">*</span></label>
<input type="text" name="email" id="email" size="30" value="" required/>
<label for="phone" id="phone">Phone</label>
<input type="text" name="phone" id="phone" size="30" value="" />
<label for="Message" id="message">Message<span class="required">*</span></label>
<textarea name="message" id="message" required></textarea>
<label for="Captcha" id="captcha">Name the small house pet that says "<i>meow</i>"<span class="required">*</span></label>
<input type="text" name="captcha" value="" required/>
<input id="submit" type="submit" name="submit" value="Send" />
</fieldset>
</form>
<div id="success">
<span>
<p>Your message was sent succssfully! I will be in touch as soon as I can.</p>
</span>
</div>
<div id="error">
<span>
<p>Something went wrong, try refreshing and submitting the form again.</p>
</span>
</div>
jQuery.validator.addMethod('answercheck', function (value, element) {
return this.optional(element) || /^\bcat\b$/.test(value);
}, "type the correct answer -_-");
<?php
$to = "mail@yourdomain.com";
$from = $_REQUEST['email'];
$name = $_REQUEST['name'];
$headers = "From: $from";
$subject = "You have a message sent from your site";
$fields = array();
$fields{"name"} = "name";
$fields{"email"} = "email";
$fields{"phone"} = "phone";
$fields{"message"} = "message";
$body = "Here is what was sent:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
$send = mail($to, $subject, $body, $headers);
?>
form {
margin:0
}
form label {
margin-bottom:.2em;
font-size:1.3rem;
line-height:1.3rem;
font-size:13px;
line-height:13px;
color:#e6e6e1;
text-shadow:0px -1px #202020
}
form label.error {
margin-bottom:1em;
font-size:1.2rem;
line-height:1.2rem;
font-size:12px;
line-height:12px;
color:#c0392b
}
form input[type="text"], form textarea {
margin-bottom:1.25em;
font-family:"Inconsolata", sans-serif;
font-size:1.4rem;
line-height:1.4rem;
font-size:14px;
line-height:14px;
box-shadow:none;
-moz-box-shadow:none;
-webkit-box-shadow:none;
background:#e6e6e6;
border:1px solid #191919;
-moz-border-radius:0.2em;
-webkit-border-radius:0.2em;
border-radius:0.2em
}
form input[type="text"]:focus, form textarea:focus {
border-color:#191919;
box-shadow:none;
-moz-box-shadow:none;
-webkit-box-shadow:none
}
form input[type="text"][disabled], form textarea[disabled] {
background:#fff
}
form input[type="text"].error, form textarea.error {
background:#e6e6e6;
border-color:#c0392b
}
fieldset {
border:0px;
margin:0;
padding:0
}
.required {
color:#e9266d
}
#success, #error {
display:none
}
#success span, #erro span {
display:block;
position:absolute;
top:0;
width:100%
}
#success span p, #error span p {
margin-top:6em
}
#success span p {
color:#9bd32d;
}
#error span p {
color:#c0392b;
}
jQuery.validator.addMethod('answercheck', function (value, element) {
return this.optional(element) || /^\bcat\b$/.test(value);
}, "type the correct answer -_-");
// validate contact form
$(function() {
$('#contact').validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
message: {
required: true
},
answer: {
required: true,
answercheck: true
}
},
messages: {
name: {
required: "come on, you have a name don't you?",
minlength: "your name must consist of at least 2 characters"
},
email: {
required: "no email, no message"
},
message: {
required: "um...yea, you have to write something to send this form.",
minlength: "thats all? really?"
},
answer: {
required: "sorry, wrong answer!"
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"process.php",
success: function() {
$('#contact :input').attr('disabled', 'disabled');
$('#contact').fadeTo( "slow", 0.15, function() {
$(this).find(':input').attr('disabled', 'disabled');
$(this).find('label').css('cursor','default');
$('#success').fadeIn();
});
},
error: function() {
$('#contact').fadeTo( "slow", 0.15, function() {
$('#error').fadeIn();
});
}
});
}
});
});
@Rasha88
Copy link

Rasha88 commented Feb 12, 2015

great!! thank you for share it

@gitmanny
Copy link

Because it uses AJAX, this code will work on a one page HTML5 website right?

@sasasa671
Copy link

@gitmanny aslong as PHP is supported on your server so you can talk with the php file. Yep.

@EwelinaWoloszyn
Copy link

Hi I've problem with this form. Validation works,but the form refreshes after submitting. I doesnt send e-mail.
I've put it in wordpress, perhaps it affected the form?Plase let me know if you have any ideas.
Here's the link: http://testtermil.pl/wordpress/kontakt/

@SZ87
Copy link

SZ87 commented Oct 12, 2015

There seems to be an issue with the success message. It's just not showing after clicking "send". I've styled the form to my liking, sending the message works (I sent it to my email.) The problem is just after clicking send, the form refreshes instantly. No confirmation message or anything. How do I fix it?

@pixim
Copy link

pixim commented May 11, 2016

Hi, Compatible Browsers IE7, IE8, IE9, IE10, IE11, Firefox, Safari, Opera, Chrome or not?

@pixim
Copy link

pixim commented May 11, 2016

@gitmanny @Malik022 @ajtroxell Hi, Compatible Browsers IE7, IE8, IE9, IE10, IE11, Firefox, Safari, Opera, Chrome or not? ,thank you

@swapnilmr
Copy link

swapnilmr commented Jun 3, 2016

What do I do if I don't want captcha in the form? I've removed captcha related css n html and made following changes in js, but it's not working:

  • Removed function.answercheck.js completely
  • Removed following from validate.js:
jQuery.validator.addMethod('answercheck', function (value, element) {
        return this.optional(element) || /^\bcat\b$/.test(value);
    }, "type the correct answer -_-");

answer: {
         required: true,
         answercheck: true
    }

Is this the right way?

Edit: It's working

@ibrahimyanik
Copy link

thanks so much

@mortensvendsen
Copy link

Hi,

How do I change the charset to UTF-8?
It looks fine when typing the form on the website but when I recieve it by e-mail "æøå" looks like this for instance: æøåæøå

Please advise,
ATB
Morten

@rameshkrr
Copy link

rameshkrr commented Nov 15, 2016

Hello, I'm trying to send a mail to gmail but I don't receive any mails after sending the form. Can anyone help me I'm a beginner. Thank you earlier.

@ysfcnky
Copy link

ysfcnky commented Nov 24, 2016

Thanks for these nice codes, but i think few classes must be added ;

<script src="jquery.validate.min.js"></script>
<script src="jquery.form.min.js"></script>

you can find them easily on the internet.

@alederodesign
Copy link

Hello,
i can't validate the select option tag. How to do it?
Thank you

@Tzikas
Copy link

Tzikas commented Mar 28, 2017

These

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.form/3.32/jquery.form.js"></script>
 <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.11.1/jquery.validate.min.js"></script>
``` must be added.  Thanks for the code

@Hakkelaar
Copy link

Hakkelaar commented Sep 17, 2017

The CSS has a flaw. One must declare the font-size in px before the font-size in rem. This way only Internet Explorer will use the font-size in px (because Internet Explorer doesn't understand rem), but all the other decent browsers will use the font-size in rem.

@imranh654
Copy link

This is not working for me!

@Mat85la
Copy link

Mat85la commented Jan 17, 2018

I have the same challenge with my HTML to PHP contact form
HTML is as follows:
!DOCTYPE html>

<title></title>
		<form action="form_process.php" method="post">

	        <div class="form-group">
	          <input type="text" class="form-control" id="name" name="name" placeholder="Name" autofocus size="20" value="" required/>
			  <div class="help-block with-errors"></div>
	        </div>
	    
	    
	        <div class="form-group form_left">
	          <input type="text" class="form-control" id="email" name="email" placeholder="Email" size="20" value="" required/>
			  <div class="help-block with-errors"></div>
	        </div>
	    
	      <div class="form-group">
	           <input type="text" class="form-control" id="phone" name="phone" onkeypress="return event.charCode >= 48 && event.charCode <= 57" maxlength="10" placeholder="Mobile No." value="" required/>
			   <div class="help-block with-errors"></div>
	      </div>
	      <div class="form-group">
	      <textarea class="form-control textarea-contact" rows="5" id="comment" name="message"  placeholder="Type Your Message/Feedback here..." type="text"></textarea>
	      <br>
      	  <button class="btn btn-default btn-send"> <span class="glyphicon glyphicon-send"></span> Send </button>
	      </div>
 		</form>
 		
 		<div id="success">
		<span>
				 <p>Your message was sent succssfully! I will be in touch as soon as possible.</p>
		</span>
		</div>
		<div id="error">
		<span>
				 <p>Something went wrong, try refreshing and submitting the form again.</p>
		</span>
		</div>
 		



    </footer>

    <!-- Js -->
   
        
        <!--validate form javascript-->
        
       <script language="JavaScript"> jQuery.validator.addMethod('answercheck', function (value, element) {
    return this.optional(element) || /^\bcat\b$/.test(value);
}, "type the correct answer -_-");

// validate contact form
$(function() {
$('#contact').validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
message: {
required: true
},
answer: {
required: true,
answercheck: true
}
},
messages: {
name: {
required: "come on, you have a name don't you?",
minlength: "your name must consist of at least 10 characters"
},
email: {
required: "no email, no message"
},
message: {
required: "um...yea, you have to write something to send this form.",
minlength: "thats all? really?"
},

          submitHandler: function(form) {
        $(form).ajaxSubmit({
            type:"POST",
            data: $(form).serialize(),
            url:"form_process.php",
            success: function() {
                $('#contact :input').attr('disabled', 'disabled');
                $('#contact').fadeTo( "slow", 0.15, function() {
                    $(this).find(':input').attr('disabled', 'disabled');
                    $(this).find('label').css('cursor','default');
                    $('#success').fadeIn();
                });
            },
            error: function() {
                $('#contact').fadeTo( "slow", 0.15, function() {
                    $('#error').fadeIn();
                });
            }
        });
    }
});

});// JavaScript Document
</script>
<!--contacts script

   <!-- end of contacts script-->
   
          
	</section>
</body>

and the contact_process.php is as follows

$value){ $message_body .= "$key: $value\n"; } $to = 'hello@gmail.com'; $subject = 'Contact Form Submit'; if (mail($to, $subject, $message)){ $success = "Message sent, thank you for contacting us!"; $name = $email = $phone = $message = $url = ''; } } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } The above cannot execute like I want it to do where it is able to send email to the user.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment