Ajax URL with variable form location - javascript

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.

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");
}

Php Ajax Form is not submitting

Hey guys I am creating a newsletter sign-up form and trying to submit it with AJAX..
Here is my form:
<div id="form-content">
<form method="POST" id="news-form" name="newsletter">
<div class="bd-input-2 form-group">
<input type="email" name="newsletter_email" placeholder="Enter your email address" required />
</div>
<div class="form-group">
<button type="submit" name="newsletter">Submit</button>
</div>
</form>
</div>
And this one is my JS file in same page as form:
$('#news-form').submit(function(e){
e.preventDefault();
$.ajax({
url: 'newsletter-submit.php',
type: 'POST',
data: $(this).serialize()
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
console.log(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
On console nothing is displaying not even an error just an empty line.
And my newsletter-submit.php file :
<?php
if(isset($_POST['newsletter'])){
$newsletter_email = filter_var($_POST['newsletter_email'],FILTER_VALIDATE_EMAIL);
if(filter_var($newsletter_email, FILTER_VALIDATE_EMAIL)){
$newsletter_email = filter_var($newsletter_email, FILTER_VALIDATE_EMAIL);
$em_check = sqlsrv_query($con, "SELECT email FROM newsletter_signups WHERE email='$newsletter_email'",array(), array("Scrollable"=>"buffered"));
$num_rows = sqlsrv_num_rows($em_check);
if($num_rows > 0){
echo "<br/><p style='color: #fff;'>Email exist in our newsletter list.</p>";
}else{
$query = "INSERT INTO newsletter_signups (email) VALUES ('{$newsletter_email}')";
$insert_newsletter_query = sqlsrv_query($con,$query);
echo '<br/><p style="color: green;">Thank you for sign up in our newsletter</p>';
}
}
}
?>
But if I add any code after php tags e.g Hello world that is displayed after the submission.
My php code was working before AJAX file
Your input field is named newsletter_email and in your php you are checking for isset($_POST['newsletter']) which is always false.

Displaying form confirmation message on form submit

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>

Html form refuses to be submitted via JQuery

So I was following an AJAX/JQuery tutorial for a registration script that will be acted upon by PHP/MySQL and will be submitted via JQuery.
Now the problem that I'm encountering is that the form submits directly to the action page, which should not be so, as it supposed to submit to script.js Here are the html code for the form.
<form method="post" id="register-form" action="transact-user.php">
<h2 class="form-signin-heading"></h2>
<div class="form-group">
<div class='row'>
<div class='col-sm-6'>
<input type='text' class='form-control' id='fname' name='fname' placeholder="First name">
</div>
<div class='col-sm-6'>
<input type='text' class='form-control' id='lname' name='lname' placeholder="Last name">
</div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Phone Number" name = "phone" id = "phone" >
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name = "email" id ="email">
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name = "password" id = "password">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password Again" name = "confirmpassword" id = "confirmpassword">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block btn-apply" type="submit" name="btn-save" id = "btn-submit"><span class="glyphicon glyphicon-log-in"></span> Register</button>
</div>
</form>
</div> <!-- /container -->
<div id = "ack"></div>
script.js
$("button#btn-submit").click(function()
{ /* validation */
/* form submit */
if ($("fname").val()=="" || $("lname").val()=="" )
$("div#ack").html("Please enter both your first name and your surname");
else
$.post($("#register-form").attr("action"),
$("#register-form: input").serializeArray(),
function(data){
$("div#ack").html(data);
});
$("#register-form").submit(function(){
return false;
})
/* form submit */
});
Finally, this is the action php script transact-user.php
<?php
if($_POST)
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$confirmpassword = $_POST['confirmpassword'];
if($email != '') {
$qry = "SELECT * FROM users WHERE email='$email'";
$result = mysqli_query($mysqli,$qry);
if($result) {
if(mysqli_num_rows($result) > 0) {
echo "Email already in use";
}
#mysqli_free_result($result);
}
else {
die("Query failed");
}
}
$activation = md5(uniqid(rand(), true));
if ($stmt = "INSERT INTO users(firstname, lastname, email, password, verification, phone)"
." values('$fname', '$lname', '$email', '$password', "
. "'$activation','$phone')" or
die("Could not perform query ".mysqli_error($mysqli))) {
$result = mysqli_query($mysqli, $stmt)
or die("The system could not register you"
. "".mysqli_error($mysqli) . "<br>" . $stmt);
if ($result){
echo "sent";
}
//echo "<a href=\"gethotel.php?hid=".$row['hotel_id'].
//
/* close statement */
//$stmt->close();
}
}
?>
The issue us because you are hooking to the click event of the submit button and are not preventing the event from completing.
Also note that your selector to build the querystring is incorrect, as there should be a space before the : and not between the : and input, eg $("#register-form :input")
To fix the issues hook to the submit event of the form and use preventDefault(). Try this:
$("#register-form").submit(function(e) {
e.preventDefault();
if ($("fname").val().trim() == "" || $("lname").val().trim() == "") {
$("div#ack").html("Please enter both your first name and your surname");
} else {
$.post(this.action, $(this).find(':input').serializeArray(), function(data) {
$("div#ack").html(data);
});
}
});

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