Displaying form confirmation message on form submit - javascript

Thought you might be able to help with this, as I sort of know what I want and how to do it but I am not overally familiar with AJAX/JS and after a certain point I just stopped taking stuff in.
Basically, I am trying to have some text appear when a user submits a form, but obviously only when the form is successfully sent. My HTMl and PHP are below, but I have no idea what I am doing beyond this point so maybe someone can give me a little hand.
<form name="contactform" action="includes/contactprocess.php" method="post">
<div class="form-group">
<input type="text" class="form-control" id="fname" name="fname" required placeholder="First Name">
</div>
<div class="form-group">
<input type="text" class="form-control" id="sname" name="sname" required placeholder="Last Name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" required placeholder="Email Address">
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" required placeholder="Message Subject">
</div>
<div class="form-group">
<textarea rows="3" name="comment" class="form-control" required placeholder="Enter Comment"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Here is the PHP thus far:
<?php
/* Set e-mail recipient */
$myemail = "myemailhere";
/* Check all form inputs using check_input function */
$fname = check_input($_POST['fname'], "Enter your first name");
$sname = check_input($_POST['sname'], "Enter your second name");
$subject = check_input($_POST['subject'], "Enter the message subject");
$email = check_input($_POST['email']);
$comment = check_input($_POST['comment'], "Enter the message you wish to be sent");
/* Error handling and sanitisation for email */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("The e-mail you have entered is not valid");
}
/* Let's prepare the message for the e-mail */
$message = "A contact form has been submitted by;
Name: $fname
Surname: $sname
E-mail: $email
Comments:
$comment
Message sent via myemailhere
";
/* Send message via mail function */
mail($myemail, $subject, $message);
if(mail($myemail, $subject, $message)) {
$data['success'] = true;
}
else{
$data['success'] = false;
}
// convert the $data to json and echo it
// so jQuery can grab it and understand what happend
echo json_encode($data);
/* Check input */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
The JS/AJAX I don't really understand:
<script>
$(document).ready(function() {
// hide the success message
$('#success').hide();
// process the form
$('form').submit(function(event) {
// get the form data before sending via ajax
var formData = {
'name' : $('input[name=name]').val(),
'number' : $('input[name=number]').val(),
'message' : $('input[name=message]').val(),
'contactSubmit' : 1
};
// send the form to your PHP file (using ajax, no page reload!!)
$.ajax({
type: 'POST',
url: 'file.php', // <<<< ------- complete with your php filename (watch paths!)
data: formData, // the form data
dataType: 'json', // how data will be returned from php
encode: true
})
// JS (jQuery) will do the ajax job and we "will wait that promise be DONE"
// only after that, we´ll continue
.done(function(data) {
if(data.success === true) {
// show the message!!!
$('#success').show();
}
else{
// ups, something went wrong ...
alert('Ups!, this is embarrasing, try again please!');
}
});
// this is a trick, to avoid the form submit as normal behaviour
event.preventDefault();
});
});
</script>

Related

Has Post request a limited number of parameters?

I'm trying to send to my server 5 parameters:
Action: will contain the name of the form, in this case "signin"
Name: Name of the person who wants to signin
Surname: Surname of the person who wants to signin
Email: Email of the person who wants to signin
Password: Password of the person who wants to signin
the problem is that my server reads only 4 parameters: Name, Surname, Email and Password, and it don't see Action!
Here's the code:
Javascript:
function signin() {
alert("OK");
var action = $(this).attr('name'); // puts in action the name of the form (this case "signin")
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: document.getElementById('signin-name').value, // Name in the form
Surname: document.getElementById('signin-surname').value, // // Surname in the form
Email: document.getElementById('singin-email').value, // Email in the form
Password: document.getElementById('singin-password').value // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
PHP - Signin.php:
<!-- Signin Form -->
<?php
require('include/header.php');
?>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
<?php require('include/footer.php');?>
PHP - Submit.php:
<?php
#Detect AJAX and POST request, if is empty exit
if((empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') or empty($_POST)){
exit("Unauthorized Acces");
}
require('inc/config.php');
require('inc/functions.php');
# Check if Login form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-login'){
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$email = $_POST['Email'];
$password = $_POST['Password'];
/* Server side PHP input validation */
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Checking Email and Password existence in DB
# Selecting the email address of the user with the correct login credentials.
$query = $db->query("SELECT Email FROM USERS WHERE Email='$email' AND Password='$password'");
$result = $query->fetch(PDO::FETCH_ASSOC);
if($query->rowCount() == 1) {
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
} else {
# Failure: Set error message
$Return['error'] = 'Invalid Login Credential.';
}
output($Return);
}
# Check if Registration form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-signin') {
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$name = $_POST['Name'];
$surname = $_POST['Surname'];
$email = $_POST['Email'];
$password = $_POST['Password'];
# Server side PHP input validation
if($name === '') {
$Return['error'] = "Please enter Full name.";
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Check Email existence in DB
$result = $db->query("SELECT Email FROM USERS WHERE Name='$name' AND Surname='$surname' AND Email='$email'");
if($result->rowCount() == 1){
# Email already exists: Set error message
$Return['error'] = 'You have already registered with us, please login.';
}else{
# Insert the new user data inside the DB
try{
$db->query("INSERT INTO `users` (`ID_user`, `Name`, `Surname`, `Email`, `Password`) VALUES (NULL, '$name', '$surname', '$email', '$password')");
}
catch (PDOException $e) {
echo $e->getMessage();
}
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
}
output($Return);
}
PHP - Functions.php
# Function to set JSON output
function output($Return=array()){
header('Content-Type: application/json; charset=UTF-8');
#exit(json_encode($Return)); # Final JSON response
echo json_encode($Return);
}
here is a screenshot of the debugger:
Debug Screenshot
function signin() {
alert("OK");
var action = $('#form-signin').attr('name'); // puts in action the name of the form (this case "signin")
// alert(action);
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: $('signin-name').val(), // Name in the form
Surname: $('signin-surname').val(), // // Surname in the form
Email: $('singin-email').val(), // Email in the form
Password: $('singin-password').val() // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
The problem is with your scope for $this. Since your Javascript is called within a BUTTON element, $this has a scope relative to the button, not the form. In trying to check what $this returns by itself, it says [object Window].
function signin() {
console.log(this);
}
Console:
[object Window]
You need to either pass this via signin(this) and backtrack to the containing form element if you plan on reusing the Javascript for other forms or just use the form id in place of this.
HTML:
<button onclick="signin(this)">
JS:
function signin(element) {
var action = element.form.getAttribute("name");
}
or just simply change the this to the form's id as Lakmal pointed out:
function signin() {
var action = $("#form-signin").attr("name");
}

Preventing page refresh on form submission stops code from executing

I have read so many solutions about preventing page reload from form submission, most of them are to return false with a "JQuery script" or preventDefault().
The problem is, if you prevent the page reload with Javascript or JQuery, the code won't be executed, so in my case, the email will not be sent. So, how could I run both?
Here is my HTML form.
<form id="myform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<p><input class="w3-input w3-padding-16" type="text" placeholder="name" required name="name"></p>
<p><input class="w3-input w3-padding-16" type="email" placeholder="email" required name="email"></p>
<p><input class="w3-input w3-padding-16" type="text" placeholder="subject" required name="subject"></p>
<p><input class="w3-input w3-padding-16" type="text" placeholder="comment" required name="comment"></p>
<p>
<button class="w3-button w3-light-grey w3-padding-large" type="submit">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
My PHP code to collect data and send email:
<?php
$name = $email = $comment = $subject = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = form($_POST["name"]);
$email = form($_POST["email"]);
$subject = form($_POST["subject"]);
$comment = form($_POST["comment"]);
$to = "myemail#gmail.com";
mail($to,$subject,$comment,$email);
}
function form($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
My JQuery:
$(document).ready(function() {
$(document).on('submit', '#myform', function() {
return false;
});
});
I got this from here
http://remotephpdevelopers.com/blog/prevent-form-submission/
seems like something you are looking for. You just need to pass event through. Hope this helps
$(“#submitButton”).click(function(event){
event.preventDefault();
//do your thing
});
Please use $.ajax method for this without page load:
$("#btn").click(function()
{
$.ajax({
type : 'POST',
url : 'url',
data : $('#form').serialize()
});
});

Ajax/php contact form sending blank emails from time to time

Well I have this contact form that sends blank emails. But I did some testing and it doesn't happens to me. The only way this could happen, I think, would be by accesing the .php file directly. If not I don't know what could be the problem. The form doesn't let you send a blank email. If this keeps happening I'm going to add a validation in the php file too, but until I find out what is the problem I don't want to ignore this messages.
This is the HTML
<form name="contactForm" id="contactForm" method="post" action="/contactEngine.php" onsubmit="return validateForm()">
<input title="Input name" type="text" name="Name" id="Name" placeholder="Nombre:" required="">
<input title="Input email" placeholder="Email:" type="email" name="Email" id="Email" required="">
<input type="text" placeholder="Subject:" name="Subjet" id="Subjet">
<textarea title="Input message" placeholder="Mensaje:" name="Message" rows="20" cols="20" id="Message" required=""></textarea>
<input title="Input result" placeholder="25 + 25 = ?" type="text" name="Captcha" id="Captcha" required="">
<p id="wrongCaptcha"> Try again </p>
<input type="submit" name="submit" value="send" class="submit-button">
</form>
This is the JS
function validateForm(e) {
e.preventDefault();
var x = document.forms["contactForm"]["Captcha"].value;
if (x != 50) {//if captcha is wrong
$("#Captcha").addClass("wrongCaptchaEntered");
$("#Captcha").css("animation-name" , "none");
setTimeout (function(){
$("#Captcha").css("animation-name" , "changeBorder");
},100);
if ($("#wrongCaptcha").css("display") == "none"){
$("#wrongCaptcha").slideDown();
}
}
else { //if captcha is correct
var formAction = $("#contactForm").attr("action");
if (formAction == "/contactEngine.php"){
var formData = $("#contactForm").serialize();
$.post( formAction, formData, function(data){
console.log (data);
$(".formulario").changeTo({content: "<h2 class='section-title BackgroundGradientBlack'>"+ data +"</h2>"});
});
}
}
return false;
}
And the PHP
<?php
$EmailFrom = "EmailFrom#test.com";
$EmailTo = "EmailTo#test.com";
$Name = Trim(stripslashes($_POST['Name']));
$Email = Trim(stripslashes($_POST['Email']));
$Subject = Trim(stripslashes($_POST['Subjet']));
$Message = Trim(stripslashes($_POST['Message']));
$email_content = "Frontpage";
$email_content .= "\nNombre: $Name";
$email_content .= "\nEmail: $Email";
$email_content .= "\nMotivo: $Subject";
$email_content .= "\nMensaje: $Message";
$email_headers = "From: <$EmailFrom>";
if (mail($EmailTo, $Subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Mensaje enviado";
} else {
http_response_code(500);
echo "Error";
}
?>
Thanks!
Probably some bot that's testing the PHP endpoint it can see in your JS and is sending data to it, trying to cause havoc. I bet if you logged the $_POST variable every time an email was sent, you'd seen a lot of spammy nonsense in some $_POST variables. Emails are blank just because the bots aren't smart enough to know which keys to use in its POSTs.

Ajax URL with variable form location

I'm sure the title will get my scoulded by the SO naz. . moderators. But I wasn't sure what to name it.
I have a form that I have saved in it's own php file. I include this form on the bottom of each page on the website. This is the form file.
This should be the minimum needed code to show my issue.
<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$errors = array();
//Validate input
//Name
if(!empty($name)) {
//Check to see that $name only contains valid characters
if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; }
}else{
$errors[] = "Name field must be filled out.";
}
//End Name
//Phone
if(!empty($phone)) {
}else{
$errors[] = "Phone field must be filled out.";
}
//End Phone
//Email
if(!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
}else{
$errors[] = "Email field must be filled out.";
}
//End Email
echo json_encode($errors);
}
?>
<!-- Action Form -->
<section id="sectActionForm">
<div class="row">
<div class="col1 col-md-6">
<img class="noPad" src="/images/banners/karateka.jpg">
</div>
<div id="col2" class="col-md-6 col-xs-12">
<form id="actionForm" class="" role="form" action="index.php" method="POST">
<h3>Get your FREE class today!</h3>
<input id="name" class="form-control" type="text" placeholder="Name" /><br/>
<input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>
<input id="email" class="form-control" type="text" placeholder="Email" />
<input class="btn btn-lg btn-block" type="submit" value="Send" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "action.include.php",
dataType: "json",
success: function(data){
alert(data);
}
})
});
</script>
<!-- END Action Form -->
My problem is that since this form could be being accessed from any page, I don't know what to put in the AJAX url section.
My DESIRED BEHAVIOR: I would like for the php errors array to be passed to the ajax so it can be displayed in a modal error box.
not sure if i'm missing something, but you would literally just put the path of the file as the url. So if the name of the form php file is myForm.php, the ajax url would be myForm.php
Try with this...
<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$errors = array();
//Validate input
//Name
if(!empty($name)) {
//Check to see that $name only contains valid characters
if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; }
}else{
$errors[] = "Name field must be filled out.";
}
//End Name
//Phone
if(!empty($phone)) {
}else{
$errors[] = "Phone field must be filled out.";
}
//End Phone
//Email
if(!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
}else{
$errors[] = "Email field must be filled out.";
}
//End Email
exit(json_encode($errors)); // exit so it doesn't send the form below
}
?>
<!-- Action Form -->
<section id="sectActionForm">
<div class="row">
<div class="col1 col-md-6">
<img class="noPad" src="/images/banners/karateka.jpg">
</div>
<div id="col2" class="col-md-6 col-xs-12">
<form id="actionForm" class="" role="form" action="index.php" method="POST">
<h3>Get your FREE class today!</h3>
<input id="name" class="form-control" type="text" placeholder="Name" /><br/>
<input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>
<input id="email" class="form-control" type="text" placeholder="Email" />
<input class="btn btn-lg btn-block" type="submit" value="Send" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
$("#actionForm").on('submit', function(event){
event.preventDefault(); // so it doesnt reload the page
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'] ?>",
dataType: "json",
success: function(data){
alert(data);
}
});
});
</script>
<!-- END Action Form -->
Where are the 'name' attributes? All I see is 'id' and $_POST submits the name and value. Did this code ever work? What am I missing?
EDIT:
Place this line of code right above your <form>: <h4 id="errors" class="error"><?php if(isset($errors) && count($errors)) echo($errors);?></h4>. Add a class called 'error' and style it the way you want. You might want to add a <br> tag to the end of each error message. Or use the explode command instead of adding the <br> tag and the echo command.

AJAX script alerts for contact form with PHP, Google reCAPTCHA, and SweetAlert

I am using an AJAX script to submit a basic contact form at the bottom of my HTML that uses Google reCAPTCHA. The html code is:
<div class="col-md-6">
<form role="form" id="form" action="form.php" method="post">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name">
<span class="help-block" style="display: none;">Please enter your name.</span>
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
<label for="exampleInputText1">Message</label>
<textarea class="form-control" rows="3" id="message" name="message" placeholder="Enter message"></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="I HAVE REMOVED MY SITE KEY"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
</div>
<button type="submit" id="Submit" data-loading-text="Sending..." class="btn btn-default">Submit</button>
</form>
</div>
<!-- Placed at the end of the document so the pages load faster -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="slick/slick.min.js"></script>
<script src="assets/js/smoothscroll.js"></script>
<script src="assets/js/jquery.stellar.min.js"></script>
<script src="assets/js/fancybox/jquery.fancybox.js"></script>
<script src="assets/js/main.js"></script>
<script src="alert/sweetalert2.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
I have created a very basic php to email me the data entered into the form.
<?php
//include CSS Style Sheet
echo "<link rel='stylesheet' type='text/css' href='alert/sweetalert2.css' />";
//include a javascript file
echo "<script type='text/javascript' src='alert/sweetalert2.min.js'></script>";
// Define some constants
define( "RECIPIENT_NAME", "Paul O'Shea" );
define( "RECIPIENT_EMAIL", "I HAVE REMOVED MY EMAIL" );
define( "EMAIL_SUBJECT", "Website Enquiry" );
$full_name;$email;$subject;$message;$captcha;
if(isset($_POST['name'])){
$name=$_POST['name'];
}if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['message'])){
$message=$_POST['message'];
}if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("ERROR!","In order to avoid SPAM mail, you must confirm you are human. Please select IM NOT A ROBOT and complete the simple challenge","error");';
echo '}, 1000); </script>';
exit;
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?I HAVE REMOVED MY SECRET KEYresponse=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo "<script type=\"text/javascript\">alert('Message Failed. Please try again'); location.href='index.html#contact';</script>";
}else
{
// If all values exist, send the email
if ( $name && $email && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $name . " <" . $email . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}
echo "<script type=\"text/javascript\">alert('Thanks for your enquiry! Your message has been sent to Paul and he will be in touch within 48hrs'); location.href='index.html#contact';</script>";
}
?>
The PHP has 3 alerts within it:
reCAPTCHA has not been run.
If reCAPTCHA fails.
Success message.
These PHP alerts work if i bypass the AJAX script, (however open a blank form.php) but don't work at all when I use the AJAX script. Therefore I get a success alert from the AJAX script - even if the reCAPTCHA has not been completed - and the form data has not been emailed.
This is my AJAX script:
<script type="text/javascript">
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
swal(
'Thanks for your enquiry!',
'Your message has been sent. Paul will be in contact soon.',
'success'
);
}
});
ev.preventDefault();
});
</script>
This gives the desired result, the email is sent, and the nice alert is shown over the original page, and when closed returns to original page. However, none of the alerts referenced in form.PHP are displayed. If user forgets to run reCaptcha - the same success alert is shown - even though there message will not be emailed.
Can anyone help me add the PHP alerts to the AJAX javascript? I tried copy and paste the same code - but am a little unsure of the appropriate way to format the code. Any help greatly appreciated! Thanks!
I would remove the <script> responses from your php script and instead use plain text, then I'd go with an AJAX approach of form submission.
There are plenty of examples using this (recommended in my opinion) approach, check the following two:
Using just jQuery: jQuery Ajax POST example with PHP
jQuery AJAX submit form
Another approach is to create one file with both your HTML and php in it,
and don't redirect your form post to another page but to itself.
However, this would invoke a page refresh.
Check the following example:
Refresh page after form submitting - Check 1st Answer
Keywords for further searching: post form, ajax, php, jquery, jquery form plugin malsup
EDIT 1 - Code
HTML/JS:
<div class="col-md-6">
<form role="form" id="form" action="form.php" method="post">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name">
<span class="help-block" style="display: none;">Please enter your name.</span>
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
<label for="exampleInputText1">Message</label>
<textarea class="form-control" rows="3" id="message" name="message" placeholder="Enter message"></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="I HAVE REMOVED MY SITE KEY"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
</div>
<button type="submit" id="Submit" data-loading-text="Sending..." class="btn btn-default">Submit</button>
</form>
</div>
<!-- Placed at the end of the document so the pages load faster -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="slick/slick.min.js"></script>
<script src="assets/js/smoothscroll.js"></script>
<script src="assets/js/jquery.stellar.min.js"></script>
<script src="assets/js/fancybox/jquery.fancybox.js"></script>
<script src="assets/js/main.js"></script>
<script src="alert/sweetalert2.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
$(document).ready(function(e) {
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if (data == "error")
{
swal("ERROR!","In order to avoid SPAM mail, you must confirm you are human. Please select IM NOT A ROBOT and complete the simple challenge","error");
}
else if (data == "fail")
{
swal("Failed", "Message Failed. Please try again!", "error");
location.href='index.html#contact';
}
else if (data == "success")
{
swal("Thanks for your enquiry!", "Your message has been sent to Paul and he will be in touch within 48hrs", "success");
location.href='index.html#contact';
}
else
{
swal("Something went wrong!", data, "error");
}
}
});
ev.preventDefault();
});
});
</script>
Your php script:
<?php
// Define some constants
define( "RECIPIENT_NAME", "Paul O'Shea" );
define( "RECIPIENT_EMAIL", "I HAVE REMOVED MY EMAIL" );
define( "EMAIL_SUBJECT", "Website Enquiry" );
$full_name;$email;$subject;$message;$captcha;
if(isset($_POST['name']))
{
$name=$_POST['name'];
if($name != filter_var($name, FILTER_SANITIZE_STRING))
{
echo "Name is not valid!";
exit(); // or exit w/e you please
}
}
else
{
echo "Name field is required!";
exit(); // or exit w/e you please
}
if(isset($_POST['email']))
{
$email=$_POST['email'];
if(! filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "Email is not valid!";
exit(); // or exit w/e you please
}
}
else
{
echo "Email field is required!";
exit(); // or exit w/e you please
}
if(isset($_POST['message']))
{
$message=$_POST['message'];
if($message != filter_var($message, FILTER_SANITIZE_STRING))
{
echo "Name is not valid!";
exit(); // or exit w/e you please
}
}
else
{
echo "Message field is required!";
exit(); // or exit w/e you please
}
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha)
{
echo 'error';
exit();
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?I HAVE REMOVED MY SECRET KEYresponse=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo 'fail';
// No need to exit() here, code ends after this anyway
}
else
{
// If all values exist, send the email
if ( $name && $email && $message )
{
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $name . " <" . $email . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
echo "success";
}
else
{
echo "Name, email and message are required!";
}
// No need to exit() here, code ends after this anyway
}
?>
EDIT 2 - Validation (Added in code as well)
You can use php's filter_var function with the available filters
to validate your input. Likewise, if a validation fails you can echo and exit accordingly with a message like echo 'other' which would invoke the last if case at the JS above (just fix the title perhaps to something like "Input error" or "Invalid input").

Categories

Resources