The script below helps with processing of a form that request number and name values, and than sends it to process.php and also displays a confirmation and hides the button that would fired the modal to the form so user cannot retry to fill the form.
Script to handle pass data to process.php
$(document).ready(function () {
function successHandler(){
console.log('Success');
$("#thanks").html(msg);
$('#form-content').modal('hide');
}
function errorHandler(){
console.log('Error');
alert("Error");
}
var nameval = $('#name').val();
var numberval = $('#number').val();
$("form#contact").submit(function(){
$.ajax({
type: "POST",
url: "process.php",
data: {
name: nameval,
number: numberval,
submit: true
},
success: function(msg){
$("#thanks").html(msg);
$('#form-content').modal('hide');
return false;
},
error: function(){
alert("Error");
return false;
}
});
return false;
});
});
The whole action does generate an email with HTML from the process.php script but does not include the data that was captured from the form, I believe there is a error within this script as I cannot find anything on the form or process.php that is using PHPMail() doing anything wrong.
Could you help?
Update
<?php
if (isset($_POST['submit'])) {
$name = ($_POST['name']);
$number = ($_POST['number']);
echo "<span class=\"alert alert-success\">THANKS! SUBMITTED</span>";
$to = "EMAIL BLANKED";
$subject = "Alert!";
$message = "name: $name number: $number";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// More headers
$headers .= 'From: <email blank>' . "\r\n";
mail($to,$subject,$message,$headers);
}
else { echo '<div class="alert alert-error">Error</div>' ; }
?>
You should put this two lines:
var nameval = $('#name').val();
var numberval = $('#number').val();
inside the submit function like this
$("form#contact").submit(function(){
var nameval = $('#name').val();
var numberval = $('#number').val();
because if you set the values of the variables before the submission of the form the inputs will most likely be empty.
Related
on my website I have an ajax form with google recaptcha. I am using event.preventdefault() to keep the page from reloading. Before I added the captcha everything was working fine. However, now whenever I try to submit the form I always get the error message that the captcha was not ticked even when it was.
If i remove the event.preventdefault() everything is working fine, even with the captcha, only that I get redirected to my submission.php.
Are google recaptcha v2 and event.preventdefault() generally incompatible?
And what can I do to have a captcha and keep the page from reloading?
EDIT
JAVASCRIPT:
$(document).ready(function() {
$("#contactform").submit(function(event) {
$(".form-group").removeClass("has-error"), $(".help-block").remove();
event.preventDefault()
var formData = {
name: $("input[name=name]").val(),
email: $("input[name=email]").val(),
message: $("textarea[name=message]").val()
};
$.ajax({
type: "POST",
url: "http://example.com/form-submission.php",
data: formData,
dataType: "json",
encode: true
}).done(function(data) {
if ( ! data.success) {
if (data.errors.name) {
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#name-group').append('<div class="help-block">' + data.errors.name + '</div>'); // add the actual error message under our input
}
if (data.errors.email) {
$('#email-group').addClass('has-error'); // add the error class to show red input
$('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
}
if (data.errors.message) {
$('#message-group').addClass('has-error'); // add the error class to show red input
$('#message-group').append('<div class="help-block">' + data.errors.message + '</div>'); // add the actual error message under our input
}
if (data.errors.captcha) {
$('#captcha-group').addClass('has-error'); // add the error class to show red input
$('#captcha-group').append('<div class="help-block">' + data.errors.captcha + '</div>'); // add the actual error message under our input
}
} else {
$("#contactheadline").append('<div class="submissionsuccess">' + data.message + "</div>");
document.getElementById("contactform").style.display = "none";
}
});
});
});
PHP:
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => '_key_',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['message']))
$errors['message'] = 'Message is required.';
if (!$res['success'])
$errors['message'] = 'Please tick the Captcha.';
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$email_from = 'form-submission#example.com';address
$to = "info#example.com";
$email_subject = "New Form submission";
$email_body = "You have received a new message from $name ($visitor_email). \n $message \r\n".
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email";
mail($to,$email_subject,$email_body,$headers);
$data['success'] = true;
$data['message'] = "Thank you for contacting us! We have received your message and will get back to you shortly.";
}
// return all data to an AJAX call
echo json_encode($data);
?>
Thank you in advance!
As i expected, you are not sending the entire form but only 3 elements (name, email and message). That's why your recaptcha is invalid, try sending the entire form instead:
var form = document.getElementById("contactform");
// or with jQuery
//var form = $("#contactform")[0];
$.ajax({
// the formData function is available in almost all new browsers.
data: new FormData(form),
// Rest of your configuration
});
Help to make a conclusion successful transmission of data. I tried in different ways, but it does not work. By clicking on the "Send" button the data is sent, but the message "Data sent successfully".
I need it to form disappeared and instead of it there was a message "Data sent successfully"
submitHandler: function(form){
var $form = $(form);
$.post('form.php', $form.serialize(), function(data){
if (!data || data.status !== 'ok') {
$form.find('input').addClass('error');
return false;
}
forms.fadeOut('slow', function(){
$('.form--success').fadeIn('fast');
});
}, 'json');
return false;
}
});
form.php
if(isset($_POST['submit'])) {
$to = "example#example.com";
$subject = "Contact Form";
$phone = $_POST['phone'];
$mail = $_POST['mail'];
$headers = "From: $phone<$mail>\r\n";
$body = "From: $phone<$mail>\r\n Phone Number: $phone\n E-Mail: $mail\n";
mail($to, $subject, $body, $headers);
exit();
}
http://37.230.210.96/ - testing site
You're not targeting the right element to fade out. You have:
var form = $(form);
To fade that out you would use this:
form.fadeOut('slow', function(){
$('.form--success').fadeIn('fast');
});
forms != form
Can anybody help me with this? I am not highly proficient in coding but know enough to get by. The issue is that the form can be filled out but in the telephone number field it won't accept spaces and 2) when it is filled out properly it does not return a value of "submitted".
Any help is greatly appreciated.....
$("#ajax-contact-form").submit(function() {
var str = $(this).serialize();
var href = location.href.replace(/dark\/|video\/|slider\/|contact\.html/g,'');
$.ajax({
type: "POST",
url: href + "contact_form/contact_process.php",
data: str,
success: function(msg) {
// Message Sent - Show the 'Thank You' message and hide the form
if(msg == 'OK') {
$(this).addClass('success').find('span:eq(1)').html('success');
} else {
$(this).addClass('error').find('span:eq(1)').html('error');
}
}
});
return false;
});
and the PHP code
<?php
include dirname(dirname(__FILE__)).'/mail.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post){
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$phone = stripslashes($_POST['phone']);
$message = stripslashes($_POST['message']);
$mail = mail(CONTACT_FORM, $phone, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail){
echo 'OK';
}
}
?>
your data is the wrong syntax you need to define it and then put the key in it i.e.
data: {str: str},
http://api.jquery.com/jQuery.ajax/
I am lost on why i am getting this internal error(500). My email info still go through when i click submit. The only problem i have is that the ajax success method is not being called so basically my callback function is never getting called on. Any help would be greatly appreciated. I have been pulling my hair out for hours on this problem.
My scipt-ajax call:
emailValidation: function(e){
e.preventDefault();
$('body, html').animate({scrollTop:0},"slow");
var valid = '';
var name = $("#f_name").val();
var email = $("#f_email").val();
var message = $("#f_message").val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(name === '' || name.length <= 2){
valid += '<p class="error">Name must be longer than 2 char.</p>';
}
if(message === '' || message.length <= 5){
valid += '<p class="error">Message must be longer than 5 char.</p>';
}
if (!(email).match(emailReg)){
valid += '<p class="error">Invalid Email</p>';
}
if (valid !== ''){
$('#form-messages').html(''+valid+'').fadeIn();
}
else {
var formData = $("#contact").serialize();//Value for sanitized form values to be paased to email.php. Value returns an array
portfolio.submitEmail(formData);
}
},
submitEmail: function(formData){
console.log(formData);
//$('#form-messages').html("Proccessing...<img src='img/processing_bar.png' alt='Proccessing' />").fadeIn('fast');
$('body, html').animate({scrollTop:0},"fast");
$.ajax({
type: 'POST',
url: 'mailer.php',
data: formData,
dataType: 'json',
success: function(result){
console.log(result.statusText);
if(result.statusText === 'OK'){
console.log('jam');
// Make sure that the formMessages div has the 'success' class.
$('#form-messages').removeClass('error');
$('#form-messages').addClass('success');
// Set the message text.
$('#form-messages').html('<p class="success">Message has been sent succesfully! Thank you '+ $('#f_name').val() +', a response will be returned in less than one business day.</p>');
$("#contact").fadeOut('slow').remove();
$('body, html').animate({scrollTop:0},"fast");
}
},
error: function(error){
console.log(error.statusText);
if(error.statusText === 'OK'){
// Make sure that the formMessages div has the 'success' class.
$('#form-messages').removeClass('error');
$('#form-messages').addClass('success');
// Set the message text.
$('#form-messages').html('<p class="success">Message has been sent succesfully! Thank you '+ $('#f_name').val() +', a response will be returned in less than one business day.</p>');
$("#contact").fadeOut('slow').remove();
$('body, html').animate({scrollTop:0},"fast");
}
},
});
},
Here is my mail.php file:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$em_name = strip_tags(trim($_POST["name"]));
$em_name = str_replace(array("\r","\n"),array(" "," "),$em_name);
$em_email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$em_message = $_POST["message"];
$em_phone = $_POST['phone'];
$em_website = $_POST['website'];
$em_hear = $_POST['hear'];
$em_startdate = $_POST['startdate'];
$em_budget = $_POST['budget'];
$to = 'theller5567#gmail.com';
$subject = 'Website Change Request';
$headers = "From: " . $em_email . "\r\n";
$headers .= "Reply-To: ". $em_email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Build the email content.
$message = "<h3>Name: ". $em_name. "\n</h3>";
$message .= "<h3>Message: ". $em_message. "\n</h3>";
$message .= "<p>Budget: ". $em_budget. "\n</p>";
$message .= "<p>Start Date: ". $em_startdate. "\n</p>";
$message .= "<p>How did you hear about us?: ". $em_hear. "\n</p>";
$message .= "<p>Email: ". $em_email. "\n</p>";
$message .= "<p>Phone: ". $em_phone. "\n</p>";
$message .= "<p>Website: ". $em_website. "\n</p>";
if (mail($to, $subject, $message, $headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
I'm trying to submit a form as an email through PHP but I'm sending the data through an AJAX function call in jQuery so the page itself doesn't refresh (in short, the user fills out the form and then when they hit submit, it sets the data to a variable and sends that to the PHP page via AJAX call, all without the page reloading) but for some reason, the emails aren't sending, but the code itself seems to function?
Here's the code that I have (just the AJAX call and the php code).
var dataString = 'name=' + name + '&email=' + email + "&subject=" + subject + '&msg=' + msg;
$.ajax ({
type: "POST",
url: "process.php",
data: dataString,
success: function() {
$("#success").show();
$( '#contactUs' ).each(function(){
this.reset();
});
}
});
PHP
<?php
if(isset($_POST['email'])) {
$email_to = "xxx#someplace.net";
$email_subject = "subject";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$message = $_POST['msg']; // required
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Message: ".clean_string($message)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email_to, $email_subject, $message, $headers);
?>
try to use this syntax for posting your variables as an object
$.ajax ({
type: "POST",
url: "process.php",
dataType: 'json'
data: {
dataString : name,
email : email,
subject :subject,
msg : msg
},
success: function() {
$("#success").show();
$( '#contactUs' ).each(function(){
this.reset();
});
}
});