Простая PHP, jQuery, and AJAX форма обратной связи

Простая PHP, jQuery, and AJAX форма обратной связи


Build a Simple PHP, jQuery, and AJAX Powered Contact Form (Updated 02/05/2014)

 

Updated 02/05/2014

I have updated the script to prevent multiple submissions by disabling all form fields upon a successful submission. I have also provided a demo in a zip file.

There are a ton of options and a ton of configurations for creating a contact form for your website. Some of them good, some of them great. Keep in mind, this is just an example, and should be treated as such. Better spam protection is a good idea, but for now we will stick with a simple to implement option.

Needed Assets

Before we begin, you will need a few things already implemented on your site. Provided is their name and link to the CDN file. Place these in the footer of your page above the closing tag.

  • jQueryhttp://code.jquery.com/jquery-latest.min.js
  • jQuery Form Plugin//cdnjs.cloudflare.com/ajax/libs/jquery.form/3.32/jquery.form.js
  • jQuery Validate//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.11.1/jquery.validate.min.js

The HTML

The form is simple HTML with a few input fields, a “spam protection” field, and a hidden confirmation message triggered via the jQuery Validate plugin AJAX success call.

<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. fade effect

view raw
contact.html
hosted with ❤ by GitHub

The CSS

Here is some base CSS for the form, you will need to make adjustments to match your sites styling.

form {
margin:
}
form label {
margin-bottom:.2em;
font-size:1.3rem;
line-height:1.3rem;
font-size:13px;
line-height:13px;
color:#e6e6e1;
text-shadow:px -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:px;
margin:;
padding:
}
.required {
color:#e9266d
}
#success, #error {
display:none
}
#success span, #erro span {
display:block;
position:absolute;
top:;
width:100%
}
#success span p, #error span p {
margin-top:6em
}
#success span p {
color:#9bd32d;
}
#error span p {
color:#c0392b;
}

view raw
style.css
hosted with ❤ by GitHub

The PHP

The PHP needed is just a basic form mail script. Change “mail@yourdomain.com” to the email the form should send to, and “You have a message sent from your site” to whatever subject you would like the email to have. This script will reside on your server as process.php and not get inserted into your page.

<?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);
?>

view raw
process.php
hosted with ❤ by GitHub

jQuery Validation

Using jQuery Validate we can assure that the form is filled out properly before being sent in, and also prevent a bit of spam using a custom function.

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();
});
}
});
}
});
});
Читайте также  Настройка на веб-сервере часового пояса и синхронизации времени для PHP и CentOS

view raw
validate.js
hosted with ❤ by GitHub

First we state the rules for the form; what is required and what is not. Including a reference to a custom function we will make named answercheck, then we have a custom submit handler that uses the jQuery Form Plugin to submit the form via AJAX to the process.php script.

Once the form submits and returns, jQuery Form Plugin detect this and carries out the jQuery in the success* or **error callbacks. All these do is fade out the form and fade in the success or error divs.

Answercheck Function

This function can be placed in an existing js file such as the previous validate.js or in it’s own file which will then need to be referenced in your HTML.

jQuery.validator.addMethod(answercheck, function (value, element) {
return this.optional(element) || /^\bcat\b$/.test(value);
}, «type the correct answer -_-«);

Our quiz question to help prevent spam is “Name the small house pet that says meow“. You can ask anything you’d like, but I enjoy cats.

Our custom validation method requires a specific answer of cat as stated at /^\bcat\b$/, and will return a custom error notification as long as the answer is incorrect.

That’s It

There you go, a simple PHP, jQuery, and AJAX powered contact form. You can see it in action on my portfolio at http://portfolio.ajtroxell.com. Feel free to submit it to see the AJAX/jQuery process after submission. Sorry, the demo is no longer available.

Discussion

Изучение PHP — интерполяция переменных... Значение переменной может быть отображено например так: $capital = "London"; echo "Capital of Great Britain is", $capital,""; Есть способ...
Простой спойлер на Jquery. Html Показать текст Текст который должен скрываться и раскрываться. Его очень много и он выезжает. Css .opened { color:green...
Парсер ссылок используя карту сайта.... Вообщем задача была такая,вставляю список доменов например: http://site1.ru/ http://site2.ru/ http://site3.ru/ Передаю через textarea в обработчик,ск...
Карусель изображений jquery. fade effect... Html разметка Jquery Код //============слайдер баннеровтоп============ $(".bannerstop > div:gt(0)").hide(); setInterval(...

Сохрани, чтобы не потерять