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 è stato inviato correttamente!</div>
<div id="error">Impossibile inviare il messaggio. Riprovare più 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.
Related
I have a form which was sending emails from the server before but all of a sudden it stopped working. I cant seem to figure out the issue. When I use the form without ajax then email works perfectly. I saw http 200 code in the dev tools and no errors. Any help would be much appreciated. Thank you.
html:
<form id="form1" class="form-action" action="" method="POST">
<input type="text" name="name" id="name" class = "name" required />
<input type="email" name="email" id="email" required />
<input type="text" name='company' id="company" class="company" required />
<textarea class= "message" name="message" id="message" required />
</textarea>
<script src="https://www.google.com/recaptcha/api.js"></script>
<div class="g-recaptcha" data-sitekey="x" data-callback="recaptcha"></div>
<button type="submit" id="submit-button">Submit</button>
<span class="success_message font-weight-bolder text-center hide" style="margin-left: 30px;">
message received.</span>
</form>
<script>
function reset_form(){
$("#form1")[0].reset();
}
function reset_success_message(){
$('.success_message').addClass('hide');
}
$(document).ready(function(){
$('#name').click(function () {
$('.success_message').addClass('hide');
});
$('.email').click(function () {
$('.success_message').addClass('hide');
});
$('.company').click(function () {
$('.success_message').addClass('hide');
});
$('#message').click(function () {
$('.success_message').addClass('hide');
});
$('#form1').submit(function (e) {
$('.success_message').addClass('hide');
e.preventDefault();
$.ajax({
url: 'serverside.php',
type: 'post',
data: $('#form1').serialize(),
success: function (response) {
if(response == 'submitted'){
reset_form();
$('.success_message').removeClass('hide');
}
}
});
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
serverside.php
<?php
$email_to = 'x#domain.com';
$email_subject = 'form submission';
$email = $_POST ['email'];
$required = array('name','email','company', 'message');
$form1_complete = FALSE;
$validation = array();
if(!empty($_POST)) {
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
foreach($required as $field) {
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
if($_POST[$field] == '') array_push($validation, $field);
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
if(count($validation) == 0) {
$email_content = 'New Comment: ' . "\n\n";
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n\n ";
}
$recaptcha_secret = "x";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true) {
mail($email_to, $email_subject, $email_content, "From:" . $email);
}
else
{
}
echo 'submitted';
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
You seem to be missing the Recaptcha secrets. Removing the Recaptcha if condition it works fine.
<?php
$email_to = 'ahmed_rises#hotmail.com'; //-----------> Invalid Email Id was added here
$email_subject = 'form submission';
$email = $_POST ['email'];
$required = array('name','email','company', 'message');
$form1_complete = FALSE;
$validation = array();
if(!empty($_POST)) {
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
foreach($required as $field) {
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
if($_POST[$field] == '') array_push($validation, $field);
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
if(count($validation) == 0) {
$email_content = 'New Comment: ' . "\n\n";
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n\n ";
}
//Recaptca Secrets are Missing?????? Random string passed!
$recaptcha_secret = "x";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret="
.$recaptcha_secret."&response=".$_POST['g-recaptcha-response']); //-----> Also Recapta response from
//the form is also missing since there its not working and neither getting passed
$response = json_decode($response, true);
//Printed the Output in which it shows the recapta Error
echo "<pre>";
print_r($response);
//If you ae to remove the Recapta Condition, the mail will be send!
// if($response["success"] === true) {
echo "==========";
echo "email_subject:".$email_subject.", email:".$email.",email_to:".$email_to;
mail($email_to, $email_subject, $email_content, "From:" . $email);
echo "==========";
// }
// else
// {
// echo "Failed";
// }
echo "<br>";
echo 'submitted';
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
Hope it helps :)
I'm working on contact page form to send emails.
I have written HTML form to get user details and performing form validations in contactform.js file. In the same JavaScript file I have written ajax POST call to call contact_mail.php.
I have found many similar questions over the internet but the problem is - in my local machine on form Submit button php is getting called, but this is not happening in remote web server.
If I avoid call to contactform.js by removing class="contactForm" from my form definition, php is getting called but I loose all the validation. :( If i call contactform.js by specifying class="contactForm" in form definition then validation are performed nicely but nothing happens on submit since no call to PHP.
I don't know what am I doing wrong...
Here is my code...
HTML form looks like this:
<form action="contactform/contact_mail.php" method="post" role="form" class="contactForm">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="phone" class="form-control" name="phone" id="phone" placeholder="Your Contact" data-rule="phone" data-msg="Please enter a valid contact number" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
</div>
</div>
This is my javascript contactform.js file
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.contactForm').submit(function(e) {
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i,
phoneExp = ^\+[0-9]{1,3}\.[0-9]{4,14}(?:x.+)?$;
/*phoneExp = /^\d{10}$/;*/
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'phone':
if (!phoneExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
else var str = $(this).serialize();
var action = $(this).attr('action');
if( ! action ) {
action = 'contactform/contact_mail.php';
}
$.ajax({
type: "POST",
url: action,
data: str,
success: function(msg) {
// alert(msg);
if (msg == 'OK') {
$("#sendmessage").addClass("show");
$("#errormessage").removeClass("show");
$('.contactForm').find("input, textarea").val("");
} else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
}
});
return false;
});
});
My contact_mail.php file
<?php
/* send mail new*/
/* start - send mail */
require_once('contactform/class.phpmailer.php');
require_once('contactform/PHPMailerAutoload.php');
require_once('contactform/class.smtp.php');
if(isset($_POST["Submit"]))
{
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$message=$_POST['message'];
$body = '<html><body>';
$body .= '<h2>Customer Enquiry </h2><br>';
$body .= '<table rules="all" style="background-color: #EBF4FA;" cellpadding="10">';
$body .= "<tr><td><strong>Name:</strong> </td><td>" . strip_tags($_POST['name']) . "</td></tr>";
$body .= "<tr><td><strong>Email:</strong> </td><td>" . strip_tags($_POST['email']) . "</td></tr>";
$body .= "<tr><td><strong>Contact No. :</strong> </td><td>" . strip_tags($_POST['phone']) . "</td></tr>";
$body .= "<tr><td><strong>Message:</strong> </td><td>" . strip_tags($_POST['message']) . "</td></tr>";
$body .= "</table>";
$body .= "</body></html>";
$to = "receiver address";
$subject = " Enquiry Form";
$headers = "From: info#xyz.com" . "\r\n" .
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
$res="OK";
if (mail($to,$subject,$body,$headers))
{
return $res;
}
else
{
return false;
}
header( "refresh:0;url=index.html");
}?>
Actually, I am learning php language at beginner level.
What should do to send mail successfully and get success or failure message.
It appears the submit form handler is not preventing the default submitted event. Try adding '''e.preventDefault()''' at the start of the handler.
I have some trouble cleaning and making my contact form working.
I'm using a template which had a captcha validation and I don't want it. There was also a "website input that I delete.
I'm a newbie in php so I don't really know what I have to remove and I don't want to start a new php/js files
My contact-send.php file is in a php folder. So I assume the action call in the html is good.
I have two other files in there ( captcha_page.php and image.php but I won't use here, will delete it, so I don't post code )
<form class="contact-form" method="post" action="php/contact-send.php">
<p class="input-block">
<input type="text" name="name" id="name" placeholder="Name *" />
</p>
<p class="input-block">
<input type="email" name="email" id="email" placeholder="Email *" />
</p>
<p class="input-block">
<textarea name="message" id="message" placeholder="Message *"></textarea>
</p>
<p class="input-block">
<button class="button turquoise submit" type="submit" id="submit"><i class="icon-paper-plane"></i></button>
</p>
</form><!--/ .contact-form-->
<?php
if (isset($_REQUEST['action'])) {
if ($_REQUEST['action'] == "contact_form_request") {
$ourMail = "xxx.xxxx#gmail.com";
$required_fields = array("name", "email", "message");
$pre_messagebody_info = "";
$errors = array();
$data = array();
parse_str($_REQUEST['values'], $data);
//check for required and assemble message
if (!empty($data)) {
foreach ($data as $key => $value) {
$name = strtolower(trim($key));
if (in_array($name, $required_fields)) {
if (empty($value)) {
if ($name == "name") {
$errors[$name] = "Please enter your Name before sending the message";
}
if ($name == "message") {
$errors[$name] = "Please enter your message ";
}
if ($name == "email") {
if (!isValidEmail($value)) {
$errors[$name] = "Please enter correct Email address";
}
}
}
}
}
}
session_start();
$verify = $_SESSION['verify'];
if ($verify != md5($data['verify'])) {
$errors["verify"] = "Please enter correctly captcha";
}
$result = array (
"is_errors" => 0,
"info" => ""
);
if (!empty($errors)) {
$result['is_errors'] = 1;
$result['info'] = $errors;
echo json_encode($result);
exit;
}
$pre_messagebody_info .= "<strong>Name</strong>" . ": " . $data['name'] . "<br />";
$pre_messagebody_info .= "<strong>E-mail</strong>" . ": " . $data['email'] . "<br />";
$pre_messagebody_info .= "<strong>Website</strong>" . ": " . $data['website'] . "<br />";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers.= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers.= "From: " . $data['email'] . "\r\n";
$after_message = "\r\n<br />--------------------------------------------------------------------------------------------------\r\n<br /> This mail was sent via contact form";
if (mail($ourMail, "Email from contact form", $pre_messagebody_info .="<strong>Message</strong>" . ": " . nl2br($data['message']) . $after_message, $headers)) {
$result["info"] = "success";
} else {
$result["info"] = "server_fail";
}
echo json_encode($result);
exit;
}
}
function isValidEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
?>
if ($('.contact-form').length) {
var $form = $('.contact-form'),
$loader = '<span>Loader...</span>';
$form.append('<div class="hide contact-form-responce" />');
$form.each(function () {
var $this = $(this),
$response = $('.contact-form-responce', $this).append('<p></p>');
$this.submit(function () {
$response.find('p').html($loader);
var data = {
action: "contact_form_request",
values: $this.serialize()
};
//send data to server
$.post("php/contact-send.php", data, function (response) {
$('.wrong-data', $this).removeClass("wrong-data");
$response.find('span').remove();
response = $.parseJSON(response);
if (response.is_errors) {
var p = $response.find('p');
p.removeClass().addClass("error");
$.each(response.info, function (input_name, input_label) {
$("[name=" + input_name + "]", $this).addClass("wrong-data");
p.append(input_label + '</br>');
});
$response.show(300);
} else {
$response.find('p').removeClass().addClass('success');
if (response.info === 'success') {
$response.find('p').append('Your email has been sent!');
$this.find('input, textarea, select').val('').attr('checked', false);
$response.show(300).delay(2500).hide(400);
}
if (response.info === 'server_fail') {
$response.find('p').append('Server failed. Send later!');
$response.show(300);
}
}
// Scroll to bottom of the form to show respond message
var bottomPosition = $response.offset().top - 50;
if ($(document).scrollTop() < bottomPosition) {
$('html, body').animate({ scrollTop : bottomPosition });
}
});
return false;
});
});
}
sorry, html, php and js are together, didn't manage to make something better...
thanks a lot guys !!!
remi
remove these lines :
$verify = $_SESSION['verify'];
if ($verify != md5($data['verify'])) {
$errors["verify"] = "Please enter correctly captcha";
}
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"
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()