i have this code on server 1
$("#send-mail").click(function () {
var name = $('input#name').val(); // get the value of the input field
var error = false;
if (name == "" || name == " ") {
$('#err-name').show(500);
$('#err-name').delay(4000);
$('#err-name').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
var emailCompare = /^([a-z0-9_.-]+)#([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input
var email = $('input#email').val().toLowerCase(); // get the value of the input field
if (email == "" || email == " " || !emailCompare.test(email)) {
$('#err-email').show(500);
$('#err-email').delay(4000);
$('#err-email').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
var comment = $('textarea#comment').val(); // get the value of the input field
if (comment == "" || comment == " ") {
$('#err-comment').show(500);
$('#err-comment').delay(4000);
$('#err-comment').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
if (error == false) {
var dataString = $('#contact-form').serialize(); // Collect data from form
$.ajax({
url: $('#contact-form').attr('action'),
type: "POST",
data: dataString,
timeout: 6000,
error: function (request, error) {
},
success: function (response) {
response = $.parseJSON(response);
if (response.success) {
$('#successSend').show();
$("#name").val('');
$("#email").val('');
$("#comment").val('');
} else {
$('#errorSend').show();
}
}
});
return false;
}
return false; // stops user browser being directed to the php file
});
then i have this other code on server 2
<?php
include 'functions.php';
if (!empty($_POST)){
$data['success'] = true;
$_POST = multiDimensionalArrayMap('cleanEvilTags', $_POST);
$_POST = multiDimensionalArrayMap('cleanData', $_POST);
//your email adress
$emailTo ="****#hotmail.com"; //"yourmail#yoursite.com";
//from email adress
$emailFrom ="contact#yoursite.com"; //"contact#yoursite.com";
//email subject
$emailSubject = "contacto teklife";
$name = $_POST["name"];
$email = $_POST["email"];
$comment = $_POST["comment"];
if($name == "")
$data['success'] = false;
if (!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email))
$data['success'] = false;
if($comment == "")
$data['success'] = false;
if($data['success'] == true){
$message = "NAME: $name<br>
EMAIL: $email<br>
COMMENT: $comment";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html; charset=utf-8" . "\r\n";
$headers = 'From: TEKLIFE <jsparrow#blackpearl.com>' . PHP_EOL .
$headers .= "Reply-to: <$email>".
'X-Mailer: PHP/' . phpversion();
mail($emailTo, $emailSubject, $message, $headers);
$data['success'] = true;
echo json_encode($data);
}
}
and this is the code of the contact form on server 1
<div id="successSend" class="alert alert-success invisible">
<strong>Well done!</strong>Your message has been sent.</div>
<div id="errorSend" class="alert alert-error invisible">There was an error.</div>
<form id="contact-form" method="post" action="http://guara.webposicionamientoweb.com.mx/pluton/php/mail.php">
<div class="control-group">
<div class="controls">
<input class="span12" type="text" id="name" name="name" placeholder="* Your name..." />
<div class="error left-align" id="err-name">Please enter name.</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<input class="span12" type="email" name="email" id="email" placeholder="* Your email..." />
<div class="error left-align" id="err-email">Please enter valid email adress.</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<textarea class="span12" name="comment" id="comment" placeholder="* Comments..."></textarea>
<div class="error left-align" id="err-comment">Please enter your comment.</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button id="send-mail" class="message-btn">Send message</button>
</div>
</div>
</form>
as you seen i send the post datas to other server,, if i click send on the contact form nothing happens...but the email is send ok... so i need the response so when i click send... the contact form fields are cleared... and the text appears ...message has been sent..
im complete newbee on this codes .. so some help are welcome¡¡
I ran your code through a jsfiddle.
And I got this error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://guara.webposicionamientoweb.com.mx/pluton/php/mail.php. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
In your server code, try adding:
header("Access-Control-Allow-Origin: *");
or replace * with your HTML's domain. This should allow the request to pass through.
Related
I have a form which I'm trying to use Recaptcha on.
I finally wound up just going with this one, which looked almost exactly as my form and PHP files did originally (so that seemed easy enough). Unfortunately, whether Recaptcha checkbox is clicked or not, the "Please check the recaptcha box" error pops up, indicating that it isn't working.
Here is the HTML:
<form class="contact__form" method="post" action="mail.php">
<!-- form message -->
<div class="row">
<div class="col-12">
<div class="contact__msg" style="display: none">
<p>Your message was sent successfully.</p>
</div>
</div>
</div>
<!-- end message -->
<!-- form element -->
<div class="row">
<div class="col-md-6 form-group">
<input name="name" type="text" class="form-control" placeholder="Name" required>
</div>
<div class="col-md-6 form-group">
<input name="email" type="email" class="form-control" placeholder="Email" required>
</div>
<div class="col-md-6 form-group">
<input name="phone" type="text" class="form-control" placeholder="Phone" required>
</div>
<div class="col-12 form-group">
<textarea name="message" class="form-control" rows="3" placeholder="Message" required></textarea>
</div>
<div class="col-12 form-group">
<div class="g-recaptcha" data-sitekey="6LfrrScdAAAAAM9UdXgQL4bHsISIEtYKW3Yca2Xm"></div>
</div>
<div class="col-12">
<input name="submit" type="submit" class="btn btn-success" value="Send Message">
</div>
</div>
<!-- end form element -->
</form>
PHP:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// access
$secretKey = '....';
$captcha = $_POST['g-recaptcha-response'];
if(!$captcha){
echo 'Please check the captcha form';
exit;
}
# FIX: Replace this email with recipient email
$mail_to = "...#domain.tld";
# Sender Data
$subject = "...";
$name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone = trim($_POST["phone"]);
$message = trim($_POST["message"]);
if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($phone) OR empty($subject) OR empty($message)) {
# Set a 400 (bad request) response code and exit.
http_response_code(400);
echo 'Please complete the form and try again';
exit;
}
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo 'Please check the the captcha form.';
} else {
# Mail Content
$content = "Name: $name\n";
$content .= "Email: $email\n\n";
$content .= "Phone: $phone\n";
$content .= "Message:\n$message\n";
# email headers.
$headers = "From: $name <$email>";
# Send the email.
$success = mail($mail_to, $subject, $content, $headers);
if ($success) {
# Set a 200 (okay) response code.
http_response_code(200);
echo 'Thank You! Your message has been sent';
} else {
# Set a 500 (internal server error) response code.
http_response_code(500);
echo 'Oops! Something went wrong, we couldnt send your message';
}
}
} else {
# Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo 'There was a problem with your submission, please try again.';
}
?>
And finally, the JS file which is being called in the HTML file with the form:
(function ($) {
'use strict';
var form = $('.contact__form'),
message = $('.contact__msg'),
form_data;
// Success function
function done_func(response) {
message.fadeIn()
message.html(response);
setTimeout(function () {
message.fadeOut();
}, 5000);
form.find('input:not([type="submit"]), textarea').val('');
}
// fail function
function fail_func(data) {
message.fadeIn()
message.html(data.responseText);
setTimeout(function () {
message.fadeOut(5000);
}, 5000);
}
form.submit(function (e) {
e.preventDefault();
form_data = $(this).serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form_data
})
.done(done_func)
.fail(fail_func);
});
})(jQuery);
that API want POST data, not GET data. for example with hhb_curl i use i've like
$captcha_response = (new hhb_curl ( 'https://www.google.com/recaptcha/api/siteverify', true ))->setopt_array ( array (
CURLOPT_POSTFIELDS => array (
'secret' => '...',
'response' => $_POST ['g-recaptcha-response'],
'remoteip' => $ip
)
) )->exec ()->getResponseBody ();
$captcha_response = json_decode ( $captcha_response, true , 999, JSON_THROW_ON_ERROR);
if($captcha_response ['success'] !== true) {
http_response_code ( 400 );
header ( "content-type: text/plain;charset=utf8" );
die ( 'reCaptcha error!: ' . hhb_return_var_dump ( $captcha_response ) );
}
Project structure is as follows
C:\xampp\htdocs\myProject\Documentation
C:\xampp\htdocs\myProject\HTML\css
C:\xampp\htdocs\myProject\HTML\images
C:\xampp\htdocs\myProject\HTML\js
C:\xampp\htdocs\myProject\HTML\videos
C:\xampp\htdocs\myProject\HTML\404.html
C:\xampp\htdocs\myProject\HTML\contact.php
C:\xampp\htdocs\myProject\HTML\index.html
C:\xampp\htdocs\myProject\PSD
I have a contact form in index.html that is controlled by a javascript file. This code stops default form submit, performs error checks and then uses ajax to make a post request to contact.php. The javascript code runs, it detects the php (see the alert in the code below just after the axjax funtion call. The value of d is the php script in the alert, but none of the debug lines in the php code get called and it never returns 'success'.
Here is the form
<form class="form-horizontal" id="phpcontactform">
<div class="control-group">
<input class="input-block-level" type="text" placeholder="Full Name" name="name" id="name">
</div>
<div class="control-group">
<input class="input-block-level" type="email" placeholder="Email ID" name="email" id="email">
</div>
<div class="control-group">
<input class="input-block-level" type="text" placeholder="Mobile Number" name="mobile" id="mobile">
</div>
<div class="control-group">
<textarea class="input-block-level" rows="10" name="message" placeholder="Your Message" id="message"></textarea>
</div>
<div class="control-group">
<p>
<input class="btn btn-danger btn-large" type="submit" value="Send Message">
</p>
<span class="loading"></span> </div>
</form>
here is the javascript
// JavaScript Document
$(document).ready(function() {
$("#phpcontactform").submit(function(e) {
e.preventDefault();
var name = $("#name");
var email = $("#email");
var mobile = $("#mobile");
var msg = $("#message");
var flag = false;
if (name.val() == "") {
name.closest(".control-group").addClass("error");
name.focus();
flag = false;
return false;
} else {
name.closest(".control-group").removeClass("error").addClass("success");
} if (email.val() == "") {
email.closest(".control-group").addClass("error");
email.focus();
flag = false;
return false;
} else {
email.closest(".control-group").removeClass("error").addClass("success");
} if (msg.val() == "") {
msg.closest(".control-group").addClass("error");
msg.focus();
flag = false;
return false;
} else {
msg.closest(".control-group").removeClass("error").addClass("success");
flag = true;
}
var dataString = "name=" + name.val() + "&email=" + email.val() + "&mobile=" + mobile.val() + "&msg=" + msg.val();
$(".loading").fadeIn("slow").html("Loading...");
$.ajax({
type: "POST",
data: dataString,
url: "http://localhost/myProject/HTML/contact.php",
cache: false,
success: function (d) {
alert("d: "+d);
$(".control-group").removeClass("success");
if(d == 'success') // Message Sent? Show the 'Thank You' message and hide the form
$('.loading').fadeIn('slow').html('<font color="green">Mail sent Successfully.</font>').delay(3000).fadeOut('slow');
else
$('.loading').fadeIn('slow').html('<font color="red">Mail not sent.</font>').delay(3000).fadeOut('slow');
}
});
return false;
});
$("#reset").click(function () {
$(".control-group").removeClass("success").removeClass("error");
});
})
And finally here is the php
<?php
echo "<script>console.log('Debug Objects:' );</script>";
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$mobile = $_REQUEST["mobile"];
$msg = $_REQUEST["msg"];
echo "<script>";
echo "alert('this also works');";
echo "</script>";
$to = "myemail#gmail.com";
if (isset($email) && isset($name) && isset($msg)) {
$subject = $name."sent you a message via Raaga";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = "From: ".$name."<br/> Email: ".$email ."<br/> Mobile: ".$mobile." <br/>Message: ".$msg;
echo "<script>alert('this maybe works');</script>";
$mail = mail($to, $subject, $msg, $headers);
if($mail)
{
echo 'success';
}
else
{
echo "<script>alert('name:'+$name);</script>";
echo 'failed';
}
}
echo "<script>alert('this finally works');</script>";
?>
I tried moving contact.php to the htdocs root but that didnt work. Have turned off all antivirus and firewalls but that didnt work either. Am at a loss. Thought php was supposed to work out of the box with xampp?
Okay so thanks to ADyson for the help. The issue was not that php isn't running, its that the mail server was not properly configured.
I have produced a site at "http://missdcall.co.uk" and have included a contact form at the bottom using Pulse CMS.
The contact form continues to return an error stating: "Sorry it seems that our mail server is not responding, Sorry for the inconvenience!"
As far as I can see, all is set-up correctly. I cannot see any errors in the code.
If anyone has any suggestions, they would be greatly appreciated!
Please find relevant files below...
home.txt
<div class="col-sm-6">
<form id="form_1" novalidate>
<div class="form-group">
<label>
Name
</label>
<input id="name" class="form-control" required />
</div>
<div class="form-group">
<label>
Email
</label>
<input id="email" class="form-control" type="email" required />
</div>
<div class="form-group">
<label>
Message
</label><textarea id="message" class="form-control" rows="4" cols="50" required></textarea>
</div>
<button class="bloc-button btn btn-d btn-lg btn-block" type="submit">
Send
</button>
</form>
</div>
form_1.php
<?php
if(empty($_POST['name']) && strlen($_POST['name']) == 0 || empty($_POST['email']) && strlen($_POST['email']) == 0 || empty($_POST['message']) && strlen($_POST['message']) == 0)
{
return false;
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'hello#missdcall.co.uk'; // Email submissions are sent to this email
// Create email
$email_subject = "Message from miss'd call.";
$email_body = "You have received a new message. \n\n".
"Name: $name \nEmail: $email \nMessage: $message \n";
$headers = "MIME-Version: 1.0\r\nContent-type: text/plain; charset=UTF-8\r\n";
$headers .= "From: joe#j-col.com\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers); // Post message
return true;
?>
formHandler.js
$(function()
{var successMsg = "Your message has been sent."; // Message shown on success.
var failMsg = "Sorry it seems that our mail server is not responding, Sorry for the inconvenience!"; // Message shown on fail.
$("input,textarea").jqBootstrapValidation(
{
preventSubmit: true,
submitSuccess: function($form, event)
{
if(!$form.attr('action')) // Check form doesnt have action attribute
{
event.preventDefault(); // prevent default submit behaviour
var processorFile = "./includes/"+$form.attr('id')+".php";
var formData = {};
$form.find("input, textarea, option:selected").each(function(e) // Loop over form objects build data object
{
var fieldData = $(this).val();
var fieldID = $(this).attr('id');
if($(this).is(':checkbox')) // Handle Checkboxes
{
fieldData = $(this).is(":checked");
}
else if($(this).is(':radio')) // Handle Radios
{
fieldData = $(this).val()+' = '+$(this).is(":checked");
}
else if($(this).is('option:selected')) // Handle Option Selects
{
fieldID = $(this).parent().attr('id');
}
formData[fieldID] = fieldData;
});
$.ajax({
url: processorFile,
type: "POST",
data: formData,
cache: false,
success: function() // Success
{
$form.append("<div id='form-alert'><div class='alert alert-success'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button><strong>"+successMsg+"</strong></div></div>");
},
error: function() // Fail
{
$form.append("<div id='form-alert'><div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button><strong>"+failMsg+"</strong></div></div>");
},
complete: function() // Clear
{
$form.trigger("reset");
},
});
}
},
filter: function() // Handle hidden form elements
{
return $(this).is(":visible");
},
});
});
I have problem with my form on my webpage. I am trying to use ajax and json to send the form values to php server, but I can't make properly json object.
My JS code
function sendJsonOpenPopout () {
$('.submitBtn').click(function(e){
e.preventDefault();
var subject = $('.subject').val();
var email = $('.email').val();
var message = $('.message').val();
var dataObject = {
subject: subject,
email: email,
message: message
}
$.ajax({
type: 'POST',
url: '../../kontakt.php',
contentType: "application/json",
dataType: 'json',
data: dataObject,
success: function(data){
alert('Items added');
},
error: function(){
console.log('You have fail');
}
//success: function(){
//var createdDiv = '<div class="divToBeCentered"><p class="dataText">Wiadomość została wysłana pomyślnie.\brDziękuję za kontakt.</p></div>';
//$('body').append(createdDiv);
//}
});
});
My PHP code
<?php
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$subject = $response[0];
$from = $response[1];
$message = $response[2];
$to = "lubycha#gmail.com";
$subject = $_POST['subject'];
$from = $_POST['email'];
$message = $_POST['message'];
$headers = "Content-Type: text/html; charset=UTF-8";
mail($to,$subject,$message,$headers);
?>
I know there is similar question already asked, but the answers didn't help me.
Thanks for helping.
I was able to get the json object and parse it on php side. Some variable might be named different, partly because some of it is pre-written code. Here are the steps I took.
Folder Structure
js/script.js
php/get_data.php
index.html
Index.html
a basic form.
<div id="feedback_panel" class="panel panel-default">
<form id="feedbackform" name="feedbackform" method="post">
<div class="form-group" id="email_wrapper" data-toggle="popover" data-container="body" data-placement="right">
<label class="control-label" for="email">E-mail:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="email#example.com" required>
<span class="help-block"> </span>
</div>
<div class="form-group" id="subject_wrapper" data-toggle="popover" data-container="body" data-placement="right">
<label class="control-label" for="subject">Subject:</label>
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" required>
<span class="help-block"> </span>
</div>
<div class="form-group" id="description_wrapper" data-toggle="popover" data-container="body" data-placement="right">
<label class="control-label" for="message">message:</label>
<textarea type="text" class="form-control" id="message" name="message" placeholder="message." required></textarea>
<span class="help-block"> </span>
</div>
<button type="submit" id="feedback_submit" class="btn btn-success">Submit</button>
</form>
</div>
script.js
upon submit, gather data and set it to an object and send to php via ajax.
$(function() {
// process the form
$('#feedbackform').submit(function(event) {
// get the form data - obj that will POSTED to get_data.php
var formData = {
'email' : $('#email').val(),
'subject' : $('#subject').val(),
'message' : $('#message').val()
};
// process the forum
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'php/get_data.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
if ( ! data.success) {
console.log(data);
} else {
console.log(data);
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
get_data.php
receives the data from script.js, do some validations, and then send and an e-mail.
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
$email;
$subject;
$message;
//check to see if the data exist, else write an error message,
function check_data(){
$user_inputs = array();
if (empty($_POST['email'])){
$errors['email'] = 'Email is required.';
return false;
}else{
$email = $_POST['email'];
array_push($user_inputs,$email);
}
if (empty($_POST['subject'])){
$errors['subject'] = 'subject is required.';
return false;
}else{
$subject = $_POST['subject'];
array_push($user_inputs,$subject);
}
if (empty($_POST['message'])){
$errors['message'] = 'message is required.';
return false;
}else{
$message = $_POST['message'];
array_push($user_inputs,$message);
}
return $user_inputs;
}
//getting array of data from check_data
$verify_data = check_data();
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
echo json_encode($data);
} else {
// show a message of success and provide a true success variable
$data['success'] = $verify_data;
$data['message'] = 'Success!';
//if everything is good, sent an email.
if($verify_data != false){
send_email($verify_data);
}
}
function send_email($info_data){
// person who it going
$to = 'Email, Some <some_email#mailinator.com>';
//subject of the email
$subject = $info_data[1];
$result = str_replace(' ', ' ', $info_data[2]);
$result = nl2br($result);
$result = wordwrap($result, 70, "\r\n");
//body of the email.
$message = "<html><body>";
$message .= "<p style = 'width: 400px;'>" . $result . "</p>";
$message .= "<br/>";
$message .= "</body></html>";
$headers = "From: Email, Some <some_email#mailinator.com>" . "\r\n" . 'Reply-To: '. $info_data[0] . "\r\n" ."X-Mailer: PHP/" . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8";
//sent mail: check to see if it was sent.
if(mail($to, $subject, $message, $headers)){
$data["went"] = "went";
$data['message'] = 'Success!';
}else{
$data["went"] = "didn't go";
$data['message'] = 'Sorry!';
}
// echo the log
echo json_encode($data);
}
?>
lot to cover, let me know if you any questions. I'll be happy to answer.
I have created a simple email form on a website - Processing it through AJAX using the jQuery library.
I know that the form is working because I am receiving the test email, but I will need for the user to know that their email has sent. Currently, there is no event happening upon success. It should be replacing the form (in div #contactform) with a success message. What am I missing here?
NOTE: I looked at the activity in Safari after submitting the form and it shows my process.php script, but it says "cancelled". Why is it doing this, and could it have something to do with why it is not showing a success message?
Here's my script:
HTML
<div id="contactform">
<form id="churchcontact" action="" method="POST">
<ul>
<li>
<label for="name">Name</label>
<span class="error error_name">Please enter your name</span>
<input id="name" type="text" name="name" />
</li>
<li>
<label for="email">Email</label>
<span class="error error_email">Please enter your email address</span>
<input id="email" type="text" name="email" />
</li>
<li>
<label for="message">Message</label>
<span class="error error_message">Please write a message</span>
<textarea id="message" name="message"></textarea>
</li>
<li>
<input class="formsubmit" type="submit" value="Send" />
<li>
</ul>
</form>
</div>
jQUERY
$(document).ready(function() {
////////////////////////////////////
//// form submit ////
////////////////////////////////////
$('#churchcontact').submit(function() {
////////////////////////////////////
//// validation ////
////////////////////////////////////
$('.error').hide();
//message
var message = $('textarea#message').val();
if(message == '') {
$('.error_message').show();
$('textarea#message').focus();
var errors = 'true';
}
//email
var email = $('input#email').val();
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length || email == '') {
$('.error_email').show();
$('input#email').focus();
var errors = 'true';
}
//name
var name = $('input#name').val();
if(name == '') {
$('.error_name').show();
$('input#name').focus();
var errors = 'true';
}
if(errors) {
return false;
} else {
////////////////////////////////////
//// process ////
////////////////////////////////////
var dataString = 'name='+ name + '&email=' + email + '&message=' + message;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "sites/all/modules/custom/churchcontact/process.php",
data: dataString,
success: function() {
$('#contactform').html("success!");
}
});
}
return false;
});
});
PHP (process.php)
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['message'];
$recipient = '[my email]';
$subject = 'Website Test';
$message = '
Name: ' . $name
. ', Email: ' . $email
. ', Message: ' . $msg;
mail($recipient, $subject, $message, $headers);
in process.php add an echo of mail():
$res = mail($recipient, $subject, $message, $headers);
echo $res; //if $res returns 1 that means mail was sent
ajax success:
...
success: function(data) {
if(data == 1){
message = "success!";
}
else{
message = "Error";
}
$('#contactform').empty().html(message);
}