HTML5 form is not sending - javascript

I am trying to send a mail with a contact form and php. Unfortunately it is not sending. A little javascript hides the contact form and displays a message, unfortunately it's just stuck at loading
My HTML
<form id="contact-form" class="form-horizontal" method="post" action="form.php">
<div class="form-group">
<input type="text" class="form-control" id="contact-name" name="contact-name" placeholder="Name">
<input type="email" class="form-control" id="contact-email" name="contact-email" placeholder="Email">
</div>
<div class="form-group">
<input type="text" class="form-control" id="contact-subject" name="contact-subject" placeholder="Subject">
<input id="human" type="text" class="form-control" name="human" placeholder="1+3=?">
</div>
<div class="form-group">
<textarea class="form-control" rows="8" id="contact-message" name="contact-message" placeholder="Message"></textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-default btn-lg" id="submit" name="submit" value="Send" formaction="form.php">
</div>
</form>
Edit: My PHP
<?php
$name = $_POST['contact-name'];
$email = $_POST['contact-email'];
$message = $_POST['contact-message'];
$from = $_POST['contact-email'];
$to = 'mail#domain.com'; // insert your Mail here
$subject = 'Hello';
$human = $_POST['human'];
$resp = null;
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
$headers = "From: $email" . "\r\n" .
"Reply-To: $email" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
if ($human == '4') { // edit the number 4 if you want anoter anti spam question
if (mail ($to, $subject, $body, $from)) {
$resp = array(
"status" => "OK",
"msg" => "Thanks! We will reply shortly."
);
} else {
$resp = array(
"status" => "ERROR",
"msg" => "Something went wrong, go back and try again"
);
}
} else if ($human != '4') {
$resp = array(
"status" => "ERROR",
"msg" => "Wrong antispam answer!"
);
}
header('Content-Type: application/json');
print json_encode($resp);
?>
This is the JS for hiding the form
$.fn.formAlert = function (resp) {
if (resp && resp.msg) {
this.html(resp.msg);
}
if (resp && resp.status) {
if (resp.status === 'OK') {
this.attr('class', 'alert alert-success');
} else {
this.attr('class', 'alert alert-danger');
}
} else {
this.attr('class', 'hidden');
}
};
EDIT: And this is the snipped for the submit
$('#contact-form').submit(function (e) {
var $this = $(this),
url = $this.attr('action');
e.preventDefault();
//disable any further form interaction
$this
.find(':input')
.attr('disabled', 'disabled')
.filter('[type=submit]') //get the submit button
.hide() //hide it
.after('<div class="loader"></div>'); //add a loader after it
$.post(url, {
data: $this.serialize(),
dataType: 'json',
success: function (resp) {
$('#contact-form-msg').formAlert(resp);
}
});
return false;
});
I really have no idea what I am missing here :( - any help is highly appreciated :)

According to the jQuery Documentation $.serialize only serializes successful controls, thus not disabled controls.
Actually your form IS posted, just empty.
Simply invert disabling and posting in your code:
$('#contact-form').submit(function (e) {
var $this = $(this),
url = $this.attr('action');
e.preventDefault();
$.ajax( { url: url,
data: $this.serialize(), type: 'post',
dataType: 'json',
success: function (resp) { console.log(resp);
$('#contact-form-msg').formAlert(resp);
}
});
//disable any further form interaction
$this
.find(':input')
.attr('disabled', 'disabled')
.filter('[type=submit]') //get the submit button
.hide() //hide it
.after('<div class="loader"></div>'); //add a loader after it
return false;
});

try:
$name = $_POST['contact-name'];
$email = $_POST['contact-email'];
$message = $_POST['contact-message'];
$from = $_POST['contact-email'];
instead of:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = $_POST['email'];

Just before the first div
Add
That should work.
form method="post"

Related

Prevent people from sending multiple forms without page refresh

I've currently got a working PHP/AJAX form. It shows a form-message when the form is sent, or when it has an error. But, the page doesn't refresh when the form is sent, so it'll be easy to send multiple emails by just a simple double click (or even more clicks). Have a look at my code:
HTML
<form action="" method="POST">
<ul class="form-style-1">
<li>
<input type="text" id="mail-name" name="name" class="field-divided" maxlength="15" placeholder="Voornaam *" /> <input type="text" id="mail-lastname" name="lastname" class="field-divided" maxlength="15" placeholder="Achternaam" >
</li>
<li>
<input type="text" id="mail-email" name="email" placeholder="E-mail *" class="field-long" maxlength="40" >
</li>
<li>
<input type ="text" id="mail-phone" name="phone" placeholder="Telefoonnummer" class="field-long" maxlength = "15">
</li>
<button class="mail-submit" id="mail-submit" type="submit" name="submit">Versturen</button>
<span style="color: #0184b2; text-align: center; font-size: 20px; margin: 0 auto; display: block; padding-top: 10px;" class="form-message"></span>
</ul>
</form>
JS
$("form").on("submit",function(event){
event.preventDefault();
var name = $("#mail-name").val();
var lastname = $("#mail-lastname").val();
var email = $("#mail-email").val();
var phone = $("#mail-phone").val();
var subject = $("#mail-subject").val();
var information = $("#mail-information").val();
$.post("donation-contact.php",
{
name: name,
lastname: lastname,
email: email,
phone: phone,
submit: "yes"
},
function(data){
$(".form-message").html( data );
}
);
});
PHP
<?php
if (isset($_POST['submit'])) {
$email_to = "#";
$email_subject = "#";
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$errorEmpty = false;
$errorEmail = false;
if (empty($name)) {
echo "<span class='form-error'>Voer de verplichte velden in!</span>";
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>Geef een geldig E-mail!</span>";
$errorEmail = true;
}
else {
$formcontent=" Naam: $name \n\n Achternaam: $lastname \n\n Email: $email \n\n Telefoon: $phone";
$mailheader = "From: ".$_POST["email"]."\r\n";
$headers = "From: ". htmlspecialchars($_POST['name']) ." <" . $_POST['email'] . ">\r\n";
$headers .= "Reply-To: " . $_POST['email'] . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($email_to, $email_subject, $formcontent, $mailheader);
echo "<span class='form-success'>De mail is verzonden!</span>";
}
}
?>
I've tried disabling the form button when it's being pressed. This works if the user doesn't make any mistakes, but it will also disable the button when it shows an error message.
Is there a way to disable the button only when the form is sent? Or to remove all the form input when the form is sent?
Thank you for your time
All you need is basically already present in your code.
You intercept the submission via
$("form").on("submit",function(event){
event.preventDefault();
// ...
This is the place to disable the submit button:
$("form").on("submit",function(event){
event.preventDefault();
$('#mail-submit').prop('disabled', true);
// ...
});
But you need a different treatment in the PHP script so that you can handle errors. Basiacally you need to send back a JSON object which will have a simple text property indicating the status (error / success) and a text property for the message (which may contain HTML).
PHP
if (empty($name)) {
$response = array('status' => 'error', 'message' => '<span class='form-error'>Voer de verplichte velden in!</span>');
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$response = array('status' => 'error', 'message' => '<span class='form-error'>Geef een geldig E-mail!</span>');
$errorEmail = true;
}
else {
// send email...
$response = array('status' => 'success', 'message' => '<span class='form-success'>De mail is verzonden!</span>');
}
// No matter what happened, send the respons as a JSON object for easy treatment in JavaScript
echo json_encode($response);
Now in JavaScript you will receive an object, instead of text in you callback function:
function(data) {
$(".form-message").html( data.message );
// If there was an error you must re-enable the submit button
if (data.status === 'error') {
$('#mail-submit').prop('disabled', false);
}
}

Javascript not getting called on form submit

I have a pretty simple form in html from which i am trying to send an email. I checked online for some tutorials sing js but most of them were not working. Here is my code the form is there but when i press submit the js function is not getting called rather it is not doing anything on the html form.
<form class="form-inline" id="contact-form" onSubmit="return false">
<center><p><input style="height:3vw;width:40vw;font-size:1.2vw;" type="text" class="form-control" size="30" placeholder=" Name" name="name" id="name" required></p>
<p><input style="height:3vw;width:40vw;font-size:1.2vw;" type="email" class="form-control" size="30" placeholder=" E-mail Address" name="email" id="email" required></p>
<p><input style="height:3vw;width:40vw;font-size:1.2vw;" type="text" class="form-control" size="30" placeholder=" Subject" name="subject" id="subject" required></p>
<p><textarea style="height:10vw;width:40vw;font-size:1.2vw;" placeholder=" Message..." class="form-control" name="message" id="message"></textarea></p>
<p><button type="submit" class="button" name="btn_submit" id="btn_submit">Send</button></p></center>
</form>
i have included the js file as it is after the <div> ending of the form
<script src="js/jquery-2.1.4.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/functions.js"></script>
functions.js file is as follows
//Contact Us
$("#btn_submit").click(function() {
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
var proceed = true;
if(user_name==""){
proceed = false;
}
if(user_email==""){
proceed = false;
}
if(user_message=="") {
proceed = false;
}
//everything looks good! proceed...
if(proceed)
{
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userMessage':user_message};
//Ajax post data to server
$.post('contact_me.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="alert-danger">'+response.text+'</div>';
}else{
output = '<div class="alert-success">'+response.text+'</div>';
//reset values in all input fields
$('.form-inline input').val('');
$('.form-inline textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
and my email handler is as follows :
<?php
if($_POST)
{
$to_Email = "email.com"; //Replace with recipient email address
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userSubject"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Subject = filter_var($_POST["userSubject"], FILTER_SANITIZE_STRING);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
$subject = $user_Subject;
$message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$headers = "From: " . strip_tags($user_Email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
//proceed with PHP email.
/*$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
*/
$sentMail = #mail($to_Email, $subject, $message_Body, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for contacting us.'));
die($output);
}
}
?>
On pressing submit the js file is not being called and there is no error in console either. Can anyone please help me out where i am making the mistake. Thank you.
You need to prevent the default form submission action which is to refresh the page.
You need to add a parameter to your function that can track the event and then call preventDefault() from that parameter:
$("#btn_submit").click(function(e) {
e.preventDefault();
...
}
Try replacing
$("#btn_submit").click(function() {
with
$(document).on("click,", "#btn_submit", function(){
You need to prevent the form from submitting, otherwise it will just directly submit and turn to the server-side.
You can do such a thing using jQuery:
$("#btn_submit").click(function(e) {
e.preventDefault();
//your code goes here after preventing submission
}

Ajax contact form not working in website

I'm just a beginner and trying to implement ajax contact form with php mailing script. But when I click on Submit nothing happens and nothing appears.
Below is my codes.
HTML
<form id="contactform" class="contact-form text-center" role="form">
<!-- IF MAIL SENT SUCCESSFULLY -->
<h6 class="success">
<span class="olored-text icon_check"></span> Your message has been sent successfully.</h6>
<!-- IF MAIL SENDING UNSUCCESSFULL -->
<h6 class="error">
<span class="colored-text icon_error-circle_alt"></span> E-mail must be valid.</h6>
<input id="cf-name" type="text" name="cf-name" placeholder="Your Name">
<input id="cf-email" type="email" name="cf-email" placeholder="Your Email">
<input id="cf-address" type="text" rows="7" name="cf-address" placeholder="Your Home Address">
<input id="cf-phone" type="text" rows="7" name="cf-phone" placeholder="Your Phone Number">
<input type="submit" class="button alt" value="Submit" id="submit" name="submit" data-style="expand-left"/>
</form>
Javascript
// Function for email address validation
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
/* =================================
CONTACT FORM
=================================== */
$("#contactform").submit(function (e) {
e.preventDefault();
var name = $("#cf-name").val();
var email = $("#cf-email").val();
var address = $("#cf-address").val();
var message = $("#cf-phone").val();
var dataString = 'name=' + name + '&email=' + email + '&address=' + address + '&phone=' + message;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
}
if (isValidEmail(email) && (message.length > 1) && (address.length > 1) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "sendmail.php",
data: dataString,
success: function () {
$('.success').fadeIn(1000);
$('.error').fadeOut(500);
}
});
}
else {
$('.error').fadeIn(1000);
$('.success').fadeOut(500);
}
return false;
});
PHP
<?php
// Get values from jquery
$name = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$to = "name#email.com";
$subject = "New Email Subscriber";
$message = " Name: " . $name . "\r\n\r\n Email: " . $email . "\r\n\r\n Address: " . $address . "\r\n\r\n Phone: " . $phone;
$from = "ContactForm";
$headers = "From:" . $from . "\r\n";
$headers .= "Content-type: text/plain; charset=UTF-8" . "\r\n";
if (#mail($to, $subject, $message, $headers)) {
echo "success";
} else {
echo "invalid";
}
Can someone please fix this code? I don't what's wrong with it.
Thanks in advance.
It may have nothing to do with Ajax but the php native mail function; I recommend use something like phpMailer since they are much more reliable than native function.

check php variable in javascript function

I've downloaded a template for web.
In this template, there is a php script to send email. In this script there is a validate() function, in which there is a variable $return_array. one of its value is $return_array['success'] that could be '0' or '1'. In another file, a javascript one, there is a click() function, that manages the value of 'success' in the php script doing if(html.success == '1')...but it does not work as expected, infact it is always '0'...what do I need to check?
Here is the html form:
<form method="POST" action="send_form_email.php" id="contactform">
<div>
<label for="name" style="color:white;">Inserisci il tuo nome</label>
<input type="text" class="input-field" id="name" name="name" value="">
</div>
<div>
<label for="email" style="color:white;">Inserisci la tua e-mail</label>
<input type="text" class="input-field" id="email" name="email" value="">
</div>
<div>
<label style="color:white;">Scrivi il tuo messaggio</label>
<textarea id="message" name="message" style="min-height: 160px;"></textarea>
</div>
<a id="button-send" href="#" title="Send Email" class="button" style="width:100%;">Invia E-Mail</a>
<div id="success">Il tuo messaggio &egrave stato inviato correttamente!</div>
<div id="error">Impossibile inviare il messaggio. Riprovare pi&ugrave tardi.</div>
</form>
and here is the function into the php
<?php
// EDIT THE 2 LINES BELOW AS REQUIRED
$send_email_to = "mail.address#email.com";
$email_subject = "Feedback subject";
function send_email($name,$email,$email_message)
{
global $send_email_to;
global $email_subject;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$email. "\r\n";
$message = "<strong>Email = </strong>".$email."<br>";
$message .= "<strong>Name = </strong>".$name."<br>";
$message .= "<strong>Message = </strong>".$email_message."<br>";
#mail($send_email_to, $email_subject, $message,$headers);
return true;
}
function validate($name,$email,$message)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['name_msg'] = '';
$return_array['email_msg'] = '';
$return_array['message_msg'] = '';
if($email == '')
{
$return_array['success'] = '0';
$return_array['email_msg'] = 'email is required';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$return_array['success'] = '0';
$return_array['email_msg'] = 'enter valid email.';
}
}
if($name == '')
{
$return_array['success'] = '0';
$return_array['name_msg'] = 'name is required';
}
else
{
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp, $name)) {
$return_array['success'] = '0';
$return_array['name_msg'] = 'enter valid name.';
}
}
if($message == '')
{
$return_array['success'] = '0';
$return_array['message_msg'] = 'message is required';
}
else
{
if (strlen($message) < 2) {
$return_array['success'] = '0';
$return_array['message_msg'] = 'enter valid message.';
}
}
return $return_array;
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$return_array = validate($name,$email,$message);
if($return_array['success'] == '1')
{
send_email($name,$email,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
and following the javascript code:
$('#button-send').click(function(event){
$('#button-send').html('Invio in corso...');
event.preventDefault();
//$('html, body').scrollTo( $('#contact'), 'fast' );
$.ajax({
type: 'POST',
url: 'send_form_email.php',
data: $('#contactform').serialize(),
success: function(html) {
if(html.success == '1')
{
$('#button-send').html('Invia E-Mail');
$('#success').show();
}
else
{
$('#button-send').html('Invia E-Mail');
$('#error').show();
console.log(html);
}
},
error: function(){
$('#button-send').html('Invia E-Mail');
$('#error').show();
console.log("not html.success");
}
});
});
EDIT:
I've edited the php part adding at the end the json_encode and content type, but when there is an error, like name missing or mail missing, I expect to see something appears near the input form, but it does not...
Use return json_encode($return_array); Instead of return $return_array;.
Json encode returns key => value pair array .
Also use dataType: "json" OR dataType: "jsonp" in ajax call.

Ajax/Json contact form is not working on this particular server

I have this landing page with contact form which is working without any problems on my regular hosting but It doesn't want to work on this VPS I was given access to. When I click "Send" button nothing is happening and email is not being sent. I checked mail() function and it seems to work on their server.
What could be the reason for ajax/json not working on this server?
Here's the JS code (core.js):
if ($('#contact').is(":visible")) {
$("#contact button").click(function() {
var name = $("#contactname").val();
var message = $("#contactmessage").val();
var email = $("#contactemail").val();
var emailReg = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$/;
// client-side validation
if(emailReg.test(email) == false) {
var emailValidation = false;
$('#contactemail').addClass("error");
}
else
$('#contactemail').removeClass("error");
if(name.length < 1) {
var nameValidation = false;
$('#contactname').addClass("error");
}
else
$('#contactname').removeClass("error");
if(message.length < 1) {
var messageValidation = false;
$('#contactmessage').addClass("error");
}
else
$('#contactmessage').removeClass("error");
if ((nameValidation == false) || (emailValidation == false) || (messageValidation == false))
return false;
$.ajax({
type: "post",
dataType: "json",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html('<p class="success">Email sent. Thank you.</p>');
}
});
return false;
});
};
The PHP file (send-email.php):
<? if($_SERVER['REQUEST_METHOD'] == "POST" ) {
$destination = 'myemail#example.com'; // change this to your email.
$email = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
$subject = $name;
$headers = "From: ".$name." <".$email.">\r\n" .
"Reply-To: ".$name." <".$email.">\r\n" .
"X-Mailer: PHP/" . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n";
mail($destination, $subject, $message, $headers);
}
And HTML:
<form class="contact" id="contact">
<div class="form">
<input type="text" name="name" placeholder="Name" id="contactname" />
<input type="text" name="email" placeholder="Email" id="contactemail" />
<textarea name="message" placeholder="Message" id="contactmessage"></textarea>
<button>Send</button>
</div>
</form>
The statement var emailValidation = false; inside IF is makes the variable emailValidation local to it. Similarly other variables too are local. Declare them in global scope, outside the conditions.
try using
$("#contact").serializeArray()

Categories