I want to make the form hide and a thank you message appear instead of it after the form is successfully submitted. I've done the below code but I cannot manage to get any action performed after the form is submitted .. it's like the 'if' function is ignored.
Below is my code:
JQuery:
$('form#contactform').submit(function(event) {
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val(),
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
//Done promise callback
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (! data.success == true) {
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
} else {
alert("An internal error has occured");
}
});
//Stop form default action
event.preventDefault();
Php:
<?php
$errors = array(); //array to hold validation errors
$data = array(); //array to pass back data
//validate variables
if (empty($_POST['name']))
$errors['name'] = 'Name is required';
if (empty($_POST['email']))
$errors['email'] = 'E-Mail is required';
if (empty($_POST['subject']))
$errors['subject'] = 'Subject is required';
if (empty($_POST['message']))
$errors['message'] = 'Please enter a message';
//Return response
if ( ! empty($errors)) { //If there are errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
//Process form
$name = $_POST['name'];
$email = $_POST['email'];
$re = $_POST['subject'];
$message = $_POST['message'];
$from = 'info#jamescremona.com';
$to = 'jmscre#gmail.com';
$subject = 'Form submission';
$body = "From: $name\n E-mail: $email\n Subject: $re\n Message: $message\n";
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
$data['success'] = true;
$data['message'] = 'Form Submitted';
}
echo json_encode($data);
Any help would be greatly appreciated. Thanks.
First error I spotted on your code :
'message' : $("#msg").val(), that is your last item in your array therefore no need for the ',' javascript expect more items after','
You need to check all you js errors in the console, they are there.
then the second error I saw,
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
show and hide does not exist in jquery they have show(); and hide(); then here : if (! data.success == true) {}
This is how your code should look :
<script type="text/javascript">
$('form#contactform').submit(function(event) {
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val()
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (!data.success) {
$('section#contact form#contactform').hide();
$('section#contact div.thxform').show();
//check which field was wrong and show the user
if(data.errors.name){
$('section#contact div.thxform').append(data.errors.name);
}
if(data.errors.email){
$('section#contact div.thxform').append(data.errors.email);
}
if(data.errors.subject){
$('section#contact div.thxform').append(data.errors.subject);
}
if(data.errors.message){
$('section#contact div.thxform').append(data.errors.message);
}
}else{
$('#successDIV').append(data.message);
}
}),
.fail(function(data){
//debugging puporses, all your php errors will be printed in the console
console.log(data);
});
//Stop form default action
event.preventDefault();
</script>
You need to tell the browser what to expect. So add the header function before your echo
header('Content-Type: application/json'); // this line here
echo json_encode($data);
UPDATE
Also your event.preventDefault(); comes last which should be the first thing you call after $('form#contactform').submit(function(event) { since you want to prevent stuff before the ajax call.
Also you PHP is echoing stuff in either case of the mail functions return value. So the json response is messed up, thus your ajax will not get proper data back.
UPDATE 2
I have the strong feeling that your PHP script is throwing errors of some sort. The mail function could be throwing a 530 error for example. So best you disable error displaying in your PHP script.
General advice for debugging this sort of stuff is web developer browser extensions to view request/response information.
Try this refactored code please:
ini_set('display_errors',0); // disable error displaying. Rather view in logs
$errors = array(); //array to hold validation errors
$data = array(); //array to pass back data
//validate variables
if (empty($_POST['name']))
$errors['name'] = 'Name is required';
if (empty($_POST['email']))
$errors['email'] = 'E-Mail is required';
if (empty($_POST['subject']))
$errors['subject'] = 'Subject is required';
if (empty($_POST['message']))
$errors['message'] = 'Please enter a message';
//Return response
if ( ! empty($errors)) { //If there are errors
$data['errors'] = $errors; // only necessary to set errors
} else {
//Process form
$name = $_POST['name'];
$email = $_POST['email'];
$re = $_POST['subject'];
$message = $_POST['message'];
$from = 'info#jamescremona.com';
$to = 'jmscre#gmail.com';
$subject = 'Form submission';
$body = "From: $name\n E-mail: $email\n Subject: $re\n Message: $message\n";
if (mail ($to, $subject, $body, $from)) {
$data['success'] = 'Your message has been sent!'; // store to $data instead of echo out
} else {
$data['errors'] = 'Something went wrong, go back and try again!'; // store to $data instead of echo out
}
}
header('Content-Type: application/json');
echo json_encode($data);
And your javascript snippet in the done function of the ajax call:
<script type="text/javascript">
$('#contactform').submit(function(event) {
event.preventDefault(); // note this one has to be at the beginning of your submit function since you do not want to submit
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val(),
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
//Done promise callback
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (data.success) { // success either exists or not
alert("Success! Form should hide now...");
$('#contactform').hide(); // an id is (should always) be unique. So you dont need this "section#contact form#contactform". It does not make sense. Also hide and show are functions and need brackets at the end
$('div.thxform').show();
} else { // then its an error
alert("An internal error has occured");
}
});
});
</script>
And the HTML i used to test this:
<form method="post" id="contactform">
Name <input type="text" name="name" value="test"><br>
Email <input type="text" name="email" value="test#localhost.com" ><br>
Subject <input type="text" name="subject" value="subject" ><br>
Message <textarea name="message" ></textarea><br>
<input type="submit">
</form>
Its because of 2 tiny mistakes:
[js code] Replace if (! data.success == true) with if (data.success == true).
[php code] add header('Content-Type: application/json'); before echoing $data
I guess the problem is here
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
because you echo a string and then a json object. Therefore when you treat data response on Javascript, it's not a json object.
Then I would do as follow in PHP
if (#mail($to, $subject, $body, $from)) {
$data['success'] = true;
$data['message'] = 'Form Submitted';
} else {
$data['success'] = false;
$data['message'] = 'Internal error';
}
echo json_encode($data);
and in Javascript
.done(function(data) {
if (typeof data !== 'object') {
alert('Expected data as object - '+typeof data+' received');
return;
}
data = jQuery.parseJSON(data);
//Errors and validation messages
if (data.success == true) {
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
} else {
alert(data.message);
}
});
Note that the # operator before mail function will not generate error messages to avoid sending a string on Javascript.
Related
I'm working on a contact website, where I want to have contact form. I want it to send data to e-mail and I want it to be checked by Google's recaptcha v3.
This is my second try. In the past, I've done it successfully without recaptcha. Now, I used this (https://codeforgeek.com/google-recaptcha-v3-tutorial/) tutorial, with following result:
script below the form
// when form is submit
$('#myform').submit(function() {
// we stoped it
event.preventDefault();
var mail = $('#email').val();
var comment = $("#sprava").val();
// needs for recaptacha ready
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('__SITE-KEY__', {action: 'create_comment'}).then(function(token) {
// add token to form
$('#myform').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$.post("form.php",{mail: mail, comment: comment, token: token}, function(result) {
if(result.success) {
alert('Thanks for message')
} else {
alert('An error occured')
}
});
});;
});
});
</script>
the names of html form fields are "email", "vyber", "sprava"
form.php
<?php
$mail;$comment;$captcha;
$mail = filter_input(INPUT_POST, 'mail', FILTER_VALIDATE_EMAIL);
$comment = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_STRING);
$captcha = filter_input(INPUT_POST, 'token', FILTER_SANITIZE_STRING);
}
function email_sending(){
$webmaster_email = "bla#bla.com";
$sender_email= "blabla#bla.com" ;
$email_address = $_REQUEST['email'] ;
$selection = $_REQUEST['vyber'] ;
$message = $_REQUEST['sprava'];
$msg =
"E-mail: " . $email_address . "\r\n" .
"I'm interested in " . $selection . "\r\n" .
"Message: " . $message ;
mail( "$webmaster_email", "You have mail", $msg, $header);
}
if($responseKeys["success"]) {
echo json_encode(array('success' => 'true'));
email_sending();
} else {
echo json_encode(array('success' => 'false'));
}
?>
The problem isn't within recaptcha part, but then I recieve e-mail, where data is missing. (it shows only variable names, not actual values). I might think it's because of naming in script, as I'm not sure what to write in declaration of variables. I'd be glad to receive any input about this problem.
I managed to solve this problem by changing server-side code like below, thanks to this Recaptcha tutorial.
// Check if form was submitted:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '__SECRET-KEY___';
$recaptcha_response = $_POST['recaptcha_response'];
// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
// Take action based on the score returned:
if ($recaptcha->success == true) {
// Verified - send email
} else {
// Not verified - show form error
}
}
I'm learning AJAX/JS and once the form has been submitted, I want AJAX to fire off the POST and return the data. This has been done and the data comes back OK and sucessfully, I just cannot get the 'alert' function to show. I get redirected to my process.php with the following:
{"success":false,"errors":{"email":"Email is required.","password":"Password is required."}}
I now need to get the above to display in an 'alert', such as alert('Password is required');
This is my 'process.js' form:
$(document).ready(function()
{
event.preventDefault();
$('form').submit(function(event)
{
var formData = {
'email' : $('input[email=email').val(),
'password' : $('input[password=password').val()
};
$.ajax({
type : 'POST',
url : 'ajax/proclogin.php',
data : JSON.stringify(formData),
dataType : 'json',
encode : true
})
// using the done promise callback
.done(function(data)
{
console.log(data);
if (!data.success)
{
if(data.errors.email)
{
//toastr.error(''+data.errors.email+'', 'Oops!');
alert('Email error');
}
if(data.errors.password)
{
//toastr.error(''+data.errors.password+'', 'Oops!');
alert('Password Error');
}
}
else
{
//toastr.success('Works!', 'WooHoo!');
alert('Works.');
}
});
});
});
This is the 'proclogin.php' file:
<?php
// proc(ess)login.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
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['password']))
$errors['password'] = 'Password is required.';
// 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;
} else {
// if there are no errors process our form, then return a message
$connection = mysqli_connect("*****","****","****","*****");
$email = mysqli_real_escape_string($connection, $_POST['email']); # Define email field
$input = mysqli_real_escape_string($connection, $_POST['password']); # Define password field
$query = mysqli_query($connection, "SELECT `Email`, `Password` FROM users WHERE Email='$email' LIMIT 1"); # Query what we need
$row = mysqli_fetch_array($query); # Fetch what we need
$p = $row['Password']; # Define fetched details
$email = $row['Email']; # Define fetched details
if(password_verify($input, $p)) # Verify input password matches hashed password in the DB.
{
#It matches, let's set a session and redirect them to the dashboard.php page.
$_SESSION['SID'] = $email;
$data['success'] = true;
$data['message'] = 'Success';
}
else
{
$data['success'] = false;
$data['message'] = 'fail';
}
// show a message of success and provide a true success variable
}
// return all our data to an AJAX call
echo json_encode($data);
?>
You have event.preventDefault(); outside of your submit handler, it should be inside.
The selector you use to get the password and email seems wrong.
You're attempting to send JSON but trying to read form data.
$(document).ready(function(){
$('form').submit(function(event) {
event.preventDefault();// prevent the form from submitting normally
var formData = {
'email' : $('input[type=email').val(), // get the value of the email input
'password' : $('input[type=password').val() // get the value of the password input
};
$.ajax({
type : 'POST',
url : 'ajax/proclogin.php',
data : formData, // send as form data
dataType : 'json',
})
...
You need to check if isset the email or password then show the alert message like this:
.done(function(data) {
if(data.errors.email) {
alert('email required');
}
else if(data.errors.password) {
alert('password required');
}
else {
alert('done');
}
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
and remove the condition if (!data.success)
I'd like to improve the contact form code (from a theme that I'm using) as it seems very basic and not secure at all (although I like in the current code the nice and smooth messages when a field is not filled in properly, or when the form is sent sucessfullly).
So, in order to make it more secure, I'd like to integrate PHPMailer to it.
Unfortunately, as I'm not very familiar with JS and PHP, I'm not sure where I should start? I'm assuming that I should somehow call PHPMailer just after //proceed with PHP email in the code below?
PHP:
<?php
if($_POST) {
$to_Email = "greg#dfsfsfsdfsfdsds.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["userEmail"]) || !isset($_POST["userSubject"]) || !isset($_POST["userMessage"])) {
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//additional php validation
if(empty($_POST["userName"])) {
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) {
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($_POST["userMessage"])<5) {
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//proceed with PHP email.
$headers = 'From: '.$_POST["userEmail"].'' . "\r\n" .
'Reply-To: '.$_POST["userEmail"].'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// send mail
$sentMail = #mail($to_Email, $_POST["userSubject"], $_POST["userMessage"] .' -'.$_POST["userName"], $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 '.$_POST["userName"] .' Thank you for your email'));
die($output);
}
}
?>
JS:
/*******************
* Contact Form JavaScript
********************/
$(document).on("ready",function() {
$("#email-form [type='submit']").click(function(event) {
event.preventDefault();
//get input field values
var user_name = $('input[name=name]').val()
var user_email = $('input[name=email]').val()
var user_subject = $('input[name=subject]').val()
var user_message = $('textarea[name=message]').val()
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userSubject':user_subject, '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="error-message"><p class="from">'+response.text+'</p></div>'
} else {
output = '<div class="success-message"><p class="seuccses">'+response.text+'</p></div>'
//reset values in all input fields
$('#email-form input').val('')
$('#email-form textarea').val('')
}
$("#result").hide().html(output).slideDown()
}, 'json')
});
//reset previously set border colors and hide all message on .keyup()
$("#email-form input, #email-form textarea").keyup(function() {
$("#result").slideUp()
})
});
I have a contact form that will be sent to an e-mail, but when I try to send I get the 500 Internal Server Error.
I already check probable errors like wrong variable name on HTML file and these stuff.
My hosting is Digital Ocean.
Here is my js code:
var form = $('#form-contact');
var formMessages = $('#form-messages');
$(form).submit( function( event ) {
event.preventDefault();
var formData = $(form).serialize();
$.ajax({
type : 'POST',
url : $(form).attr('action'),
data : formData,
beforeSend: function(){
$(".load").show();
},
})
.done( function( response ) {
$(".load").hide();
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
$('#form-contact input').val('');
$('#form-contact textarea').val('');
})
.fail( function( data ) {
$(".load").hide();
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Sending
if ( data.response !== '' ) {
$(formMessages).text( data.responseText );
} else {
$(formMessages).text( 'error.' );
}
});
} );
And here, my PHP code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["user_name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["user_email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["user_message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "error.";
exit;
}
// Set the recipient email address.
$recipient = "mail#here.com";
// Set the email subject.
$subject = "New contact from " . $name;
// Build the email content.
$email_content = "Name: ". $name;
$email_content .= "\nE-mail: ". $email;
$email_content .= "\n\nMessage:\n " . $message;
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thanks, your message was sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "OOps! Sorry, error.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "Problem with your request!";
}
That 500 is coming from your own code: http_response_code(500);
The reason your getting it is because mail() is returning false, which means that it's not configured properly. You'll need to install and set up postfix or fakesendmail.
I've tested my site's mailing with a different script - just to make sure it wasn't the host, and it's working fine.
I'm not sure why my code isn't working. I've included all my contact forums code except the html. It seems to not be loading the php, as it doesn't show any error messages when I put in an invalid email etc. - it just refreshes the page it seems.
Help is much appreciated, thanks everyone.
<!-- Contact Form Js -->
<script type="text/javascript">
// contact form js
jQuery(document).ready(function($) {
$("#ajax-contact-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "inc/contact-process.php",
data: str,
success: function(msg) {
// Message Sent? Show the 'Thank You' message and hide the form
if(msg == 'OK') {
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
setTimeout("location.reload(true);",7000);
} else {
result = msg;
}
$('#note').html(result);
}
});
return false;
});
});
</script>
<!-- End Contact -->
PHP - 'contact-processes'
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/
*/
include dirname(dirname(__FILE__)).'/config.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'functions.php';
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name)
{
$error .= 'Please enter your name.<br />';
}
// Check email
if(!$email)
{
$error .= 'Please enter an e-mail address.<br />';
}
if($email && !ValidateEmail($email))
{
$error .= 'Please enter a valid e-mail address.<br />';
}
// Check message (length)
if(!$message || strlen($message) < 15)
{
$error .= "Please enter your message. It should have at least 15 characters.<br />";
}
if(!$error)
{
ini_set("sendmail_from", WEBMASTER_EMAIL); // for windows server
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
echo 'OK';
}
}
else
{
echo '<div class="notification_error">'.$error.'</div>';
}
}
?>
PHP - 'functions'
<?php
function ValidateEmail($value)
{
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($value == '') {
return false;
} else {
$string = preg_replace($regex, '', $value);
}
return empty($string) ? true : false;
}
?>
PHP - 'config'
<?php
define("WEBMASTER_EMAIL", 'snip#myemail.com');
?>