Ajax Form Submit not stay on same page - php

I have designed a Sidebar Floating Form with PhP/Ajax.
Here is the Link: http://logohour.com/form.html
Everything is fine but when a visitor fill and submit the form it routes to anther page for the confirmation.
I am using almost the same coding for clickable form and its working fine but here on this sidebar floating form somewhere I am mistaking may be in Ajax or PHP.
Ajax you may find in Page Source, Here is my PHP:
<?php
// Define some constants
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "example#gmail.com" );
define( "EMAIL_SUBJECT", "SiderBar Visitor Message" );
// Read the form values
$ssuccess = false;
$Name = isset( $_POST['Name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['Name'] ) : "";
$Email = isset( $_POST['Email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Email'] ) : "";
$Phone = isset( $_POST['Phone'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Phone'] ) : "";
$Country = isset( $_POST['Country'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Country'] ) : "";
$Select = isset( $_POST['Select'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Select'] ) : "";
$Message = isset( $_POST['Message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['Message'] ) : "";
// If all values exist, send the email
if ( $Name && $Email && $Phone && $Country && $Select && $Message ) {
$msgToSend = "Name: $Name\n";
$msgToSend .= "Email: $Email\n";
$msgToSend .= "Phone: $Phone\n";
$msgToSend .= "Sender Country: $Country\n";
$msgToSend .= "Sender Select: $Select\n";
$msgToSend .= "Message: $Message";
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $Name . " <" . $Email . ">";
$ssuccess = mail( $recipient, EMAIL_SUBJECT, $msgToSend, $headers );
}
// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
echo $ssuccess ? "ssuccess" : "error";
} else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<?php if ( $ssuccess ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$ssuccess ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>
Here is the AJAX Source Code
var messageDDelay = 2000; // How long to display status messages (in milliseconds)
// Init the form once the document is ready
$(init);
// Initialize the form
function init() {
// Hide the form initially.
// Make submitForm() the form's submit handler.
// Position the form so it sits in the centre of the browser window.
// When the "Send us an email" link is clicked:
// 1. Fade the content out
// 2. Display the form
// 3. Move focus to the first field
// 4. Prevent the link being followed
$('a[href="#contact_form"]').click(function() {
$('#content').fadeTo('slow', .2);
$('#contact_form').fadeIn('slow', function() {
$('#Name').focus();
})
return false; });
// When the "Cancel" button is clicked, close the form
$('#cancel').click(function() {
$('#contact_form').fadeOut();
$('#content').fadeTo('slow', 1);
});
// When the "Escape" key is pressed, close the form
$('#contact_form').keydown(function(event) {
if (event.which == 27) {
$('#contact_form').fadeOut();
$('#content').fadeTo('slow', 1);}});}
// Submit the form via Ajax
function submitFForm() {
var contact_form = $(this);
// Are all the fields filled in?
if (!$('#Name').val() || !$('#Email').val() || !$('#Phone').val() || !$('#Country').val() || !$('#Select').val() || !$('#Message').val()) {
// No; display a warning message and return to the form
$('#incompleteMMessage').fadeIn().delay(messageDDelay).fadeOut();
contact_form.fadeOut().delay(messageDDelay).fadeIn();
} else {
// Yes; submit the form to the PHP script via Ajax
$('#sendingMMessage').fadeIn();
contact_form.fadeOut();
$.ajax({
url: contact_form.attr('action') + "?ajax=true",
type: contact_form.attr('method'),
data: contact_form.serialize(),
ssuccess: submitFFinished }); }
// Prevent the default form submission occurring
return false; }
// Handle the Ajax response
function submitFFinished(response) {
response = $.trim(response);
$('#sendingMMessage').fadeOut();
if (response == "ssuccess") {
// Form submitted ssuccessfully:
// 1. Display the ssuccess message
// 2. Clear the form fields
// 3. Fade the content back in
$('#successMMessage').fadeIn().delay(messageDDelay).fadeOut();
$('#Name').val("");
$('#Email').val("");
$('#Phone').val("");
$('#Country').val("");
$('#Selct').val("");
$('#Message').val("");
$('#content').delay(messageDDelay + 500).fadeTo('slow', 1);
} else {
// Form submission failed: Display the failure message,
// then redisplay the form
$('#failureMMessage').fadeIn().delay(messageDDelay).fadeOut();
$('#contact_form').delay(messageDDelay + 500).fadeIn(); } }

use your function like this:
$("#contact_form").submit(submitFForm);

You are not calling the submitFForm() function. Try setting a click event to the submit button or setting the "submit" event to the form, e.g:
$("#contact_form").submit(function(e) {
submitFForm();
e.preventDefault(); // avoid to execute the actual submit of the form.
});

I'm not sure if I understand correctly, but I think you're saying that this code isn't functioning correctly:
$('a[href="#contact_form"]').click(function() {
$('#content').fadeTo('slow', .2);
$('#contact_form').fadeIn('slow', function() {
$('#Name').focus();
})
return false;
});
Is that right? If so, try replacing it with this:
$('#sendMMessage').click(function(event) {
event.preventDefault();
$('#content').fadeTo('slow', .2);
$('#contact_form').fadeIn('slow', function() {
$('#Name').focus();
});
alert('successfully stopped the other page loading');
return false;
});
Using both event.preventDefault() and return false is the correct way to stop the expected redirect. Your jQuery selector also needed to be corrected.

$('#sendMMessage').click(function(e){
e.preventDefault();
.... ajax ...etc
})
You have to annulate the default submit behaviour.

Related

Cant get google recaptcha v2 to prevent form submission

So I can successfully get the captcha to validate, using the following code.
</p>
<?php
if(isset($_POST['g-recaptcha-response'])){
echo verify($_POST['g-recaptcha-response']);
}
function verify($response) {
$ip = $_SERVER['blank']; //server Ip
$key="secretkey"; // Secret key
//Build up the url
$url = 'https://www.google.com/recaptcha/api/siteverify';
$full_url = $url.'?secret='.$key.'&response='.$response.'&remoteip='.$ip;
//Get the response back decode the json
$data = json_decode(file_get_contents($full_url));
//Return true or false, based on users input
if(isset($data->success) && $data->success == true) {
return True;
}
return False;
}
?>
<p style="text-align: justify;">
<script type="text/javascript">
function verify(){
var serializedValues = jQuery("#infoForm").serialize();
jQuery.ajax({ type: 'POST',url:"verify.php",data: serializedValues,success:function(result){
if(result){
$('#show').html('Your Form Successfully Submitted');
$('.formwrap').hide(result);
return true;
}
}});
$('#show').html('Please Enter Valid Captcha');
return false;
}
var onloadCallback = function() {
grecaptcha.render('captcha_ele', {
'sitekey' : 'Enter Your Site Key Here', // Site key
});
};
</script>
However, when I click submit, regardless of what the captcha says, form will still submit. My email form process is as follows...
<!-- language: lang-css -->
$("#blank").submit(function() {
$.post('assets/php/email-process.php', {name: $('#name').val(), email: $('#email').val(), message: $('#message').val(), myFormSubmitted: 'yes'},
function(data) {
$("#formResponse").html(data).fadeIn('100');
$('#name, #email, #message').val(''); /* Clear the inputs */
}, 'text');
return false;
});
<?php
if ($_POST['leaveblank'] != '' or $_POST['dontchange'] != 'http://') {
// display message that the form submission was rejected
}
else {
// accept form submission
$to = 'info#blank'; // Replace with your email
$subject = 'Message from website visitor'; // Replace with your $subject
$headers = 'From: ' . $_POST['email'] . "\r\n" . 'Reply-To: ' . $_POST['email'];
$message = 'Name: ' . $_POST['name'] . "\n" .
'E-mail: ' . $_POST['email'] . "\n" .
'Subject: ' . $_POST['subject'] . "\n" .
'Message: ' . $_POST['message'];
mail($to, $subject, $message, $headers);
if( $_POST['copy'] == 'on' )
{
mail($_POST['email'], $subject, $message, $headers);
}
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
?>
I use this which works for me. Put a js function in your form submit to validate the re-captcha:
<form action="/sign-visitors-log/" method="post" id="VisitorsLogForm" onsubmit="return validateRecaptcha();">
Then some js to stop the form submit if the user didn't tick the check box:
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("not validated");
return false;
} else {
alert("validated");
return true;
}
}
You can swap out the alerts for toast or as you are doing some elements on the page.
HTH
In a separate js file (at least: no inline call to a function), you have to check if the captcha can validate. Like so:
jquery('form').on('submit',function(e){
if(grecaptcha.getResponse() === "") {
e.preventDefault();
alert('Error: \n please validate the Captcha test');
}
});
You don't have to check if the test passive as true, you have already prevented the form to be sent with this method.
This is a simpler model that does the job
document.querySelector(".form").addEventListener("submit", (event)=>{
const response = grecaptcha.getResponse();
if (response.length === 0) {
event.preventDefault();
alert("Please verify that you are human!");
}
})
<!--reCAPTCHA v2 -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form action="/" method="POST" class"form">
<!--Please register as a developer and add "your_site_key" you will find it on https://www.google.com/recaptcha/admin/create-->
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
</form>

Send data from php back to Ajax

So I submit my form with Ajax like so
$("#submitform").click(function(e){
e.preventDefault();
var form_data = $("#contactfrm").serialize();
$.ajax({
type: "POST",
url: "/ltlcreation-new/wordpress/wp-content/themes/LTLCreation/includes/form-handler.php",
data: form_data,
error: function(){
alert("failed");
},
success: function(json_data){
console.log(json_data);
alert("success");
},
})
});
In my form-handler.php i catch the from errors
<?php
if(isset($_POST['submit'])) {
//include validation class
include 'validate.class.php';
//assign post data to variables
$name = #($_POST['name']);
$email = #($_POST['email']);
$message = #($_POST['message']);
$phone = #($_POST["phone"]);
//echo $name, $email, $message, $phone;
//start validating our form
$v = new validate();
$v->validateStr($name, "name", 3, 75);
$v->validateEmail($email, "email");
$v->validateStr($message, "message", 5, 1000);
$v->validateStr($phone, "phone", 11, 13);
if(!$v->hasErrors()) {
$to = "lukelangfield001#googlemail.com";
$subject = "Website contact form ";
$mailbody = $message . "\n" . "from " . $name . "\n" . $phone;
$headers = "From: $email";
mail($to, $subject, $mailbody, $headers);
echo "success";
} else {
//set the number of errors message
$message_text = $v->errorNumMessage();
//store the errors list in a variable
$errors = $v->displayErrors();
//get the individual error messages
//$nameErr = $v->getError("name");
//$emailErr = $v->getError("email");
//$messageErr = $v->getError("message");
//$phoneErr = $v->getError("phone");
echo $message_text; echo $errors;
$output = array($message_text);
echo json_encode($output);
}//end error check
}// end isset
These errors usually look like something like this
There were 4 errors sending your message!
Name must be at least 3 characters long.
Please enter an Email Address.
Message must be at least 5 characters long.
Phone must be at least 11 characters long.
["There were 4 errors sending your message!\n"]
I've tried to jSon encode the output and the in the success in ajax pull the json data out, however it just keeps returning an empty string like so
(an empty string)
My question is can you send data back from PHP to Ajax, if so I am doing this completely wrong?
You can output anything other than the json string so echo "success"; would make t. Use your debuggers Network response output tab to see that this is properly encoded.
Also don't use
$name = #($_POST['name']);
use instead
$name = isset($_POST['name']) ? $_POST['name'] : '';
If you still have a blank page make sure you have display errors set.
error_reporting(E_ALL);
ini_set('display_errors', 1);
I am an idiot I still had this in my PHP file which means the form wasn't firing or returning a response, silly me, glad i finally figured it out though
if(isset($_POST['submit'])) {
Thanks for the help guys
Here is an example of an Ajax contact form you can use:
Ajax.js
$(document).ready(function(){
$("#btn").click(function(){
var username=$("#name").val();
var email=$("#email").val();
var dis=$("#dis").val();
var process=true;
if(username=="")
process=false;
if(email=="")
process=false;
if(dis=="")
process=false;
if(process){
var dataString="name="+username + "&email="+email+ "&message="+dis;
$("#res").html('<span>Sending...</span><img src="a.gif">');
$.ajax({
url:"b.php",
type:"POST",
data:dataString,
success:function(data){
document.getElementById("name").value='';
document.getElementById("email").value='';
document.getElementById("dis").value='';
$("#res").html(data);
}
});
}else{
alert("fill all fields");
}
});
});
and b.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajax") || die("erro");
if(isset($_POST['name'])){
mysql_real_escape_string(htmlentities($name=$_POST['name']));
mysql_real_escape_string(htmlentities($email=$_POST['email']));
mysql_real_escape_string(htmlentities($message=$_POST['message']));
if(!empty($name) && !empty($email) && !empty($message)){
if(mysql_query("INSERT INTO `users` (name,email,message) VALUES('$name','$email','$message') ")){
echo 'The massage has been send';
}else{
echo mysql_error();
}
}
}
?>
enjoy that....
You have the following:
success: function(json_data){
While json_data is simply nothing. It should be
success: function(data){

Position PHP code with CSS

I have a form that is positioned on the page with HTML, if the user completes the form then they are thanked with a PHP message. Because the form is positioned with <form id="formIn"> CSS the PHP text is now in the wrong position, does anyone have an idea how this can be positioned so that the PHP echo text is nest to the form?
I have tried to include the code in PHP, i.e.
<div id=\"text\">
But no joy.
Code used so far is:
<?php
echo "* - All sections must be complete"."<br><br>";
$contact_name = $_POST['contact_name'];
$contact_name_slashes = htmlentities(addslashes($contact_name));
$contact_email = $_POST['contact_email'];
$contact_email_slashes = htmlentities(addslashes($contact_email));
$contact_text = $_POST['contact_text'];
$contact_text_slashes = htmlentities(addslashes($contact_text));
if (isset ($_POST['contact_name']) && isset ($_POST['contact_email']) && isset ($_POST['contact_text']))
{
if (!empty($contact_name) && !empty($contact_email) && !empty($contact_text)){
$to = '';
$subject = "Contact Form Submitted";
$body = $contact_name."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject,$body,$headers))
{
echo "Thank you for contacting us.";
}else{
echo 'Error, please try again later';
}
echo "";
}else{
echo "All sections must be completed.";
}
A good way for doing this is to create a div for displaying messages in the form page and return back from the php script to the form page including form.html?error=email or form.html?success to the url. Then with javascript you can identify when this happens and display a message or another.
Comment if you need some code examples.
EDIT:
Imagine your php script detects that email field is not filled, so it would return to the form webpage with a variable in the url:
<?php
if(!isset($_POST["email"]){
header("location:yourformfile.html?error=email")
}
?>
Then, in your form webpage you have to add some javascript that catches that variable in the URL and displays a message in the page:
Javascript:
function GetVars(variable){
var query = window.location.search.substring(1); //Gets the part after '?'
data = query.split("="); //Separates the var from the data
if (typeof data[0] == 'undefined') {
return false; // It means there isn't variable in the url and no message has to be shown
}else{
if(data[0] != variable){
return false; // It means there isn't the var you are looking for.
}else{
return data[1]; //The function returns the data and we can display a message
}
}
}
In this method we have that data[0] is the var name and data[1] is the var data. You should implement the method like this:
if(GetVars("error") == "email"){
//display message 'email error'
}else if(GetVars("error") == "phone"){
//dislpay message 'phone error'
}else{
// Display message 'Success!' or nothing
}
Finally, for displaying the message I would recommend creating a div with HTML and CSS and animate it to appear and disappear with jQuery. Or just displaying an alert alert("Email Error");
Just create a <div> before or after your form and put IF SUBMIT condition on it.
Like,
<?php
if(isset($_POST['submit']))
{ ?>
<div>
<!-- Your HTML message -->
</div>
<?php } ?>
<form>
</form>

Trying To Create A Javascript Alert Window That Doesn't Reload The Page When OK Is Clicked

I have a PHP form that I've set up with a POST method. When all the fields aren't filled out I have a Javascript alert box that pops up and states 'Please fill out all fields!' When I click 'OK' on the alert window it reloads the form behind it clearing all the data that was entered. Is there a function that can keep the alert box's OK button from reloading the entire page? Here's my code:
<?php
if (isset($_POST['brandname']) && isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email']) && isset($_POST['website'])){
$brandname = $_POST['brandname'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$website = $_POST['website'];
if(!empty($brandname) && !empty($firstname) && !empty($lastname) && !empty($email)){
$to = 'matt#miller-media.com';
$subject = 'Submission Form';
$body = $firstname;
$headers = 'From: '.$email;
if (#mail($to, $subject, $body, $headers)){
}
}else{
echo '<script type="text/javascript">
window.alert("Please fill out all fields!")
</script>';
}
}
?>
You are alerting your user after posting response ... in this case I would re-post the whole form again with its values set to $_POST or variables that were set using it, for example :
<input type='text' name='brandname' value='<?php echo $_POST['brandname'];?>' />
or :
<input type='text' name='brandname' value='<?php echo $brandname; ?>' />
and so on
But in this case I recommend using client-side validation on the form (Using javascript)
Yeah i assume you need something like this:
<script type="text/javascript">
function do_some_validation(form) {
// Check fields
if (! /* Contition 1 */ ) return false;
if (! /* Contition 2 */ ) return false;
if (! /* Contition 3 */ ) return false;
form.submit();
}
</script>
<form onsubmit="do_some_validation(this) return false;" action="script.php" method="post">
// Fields
</form>
This will only submit the form once all JavaScript conditions in do_some_validation are met... Please note this is not advised over and above PHP validation, this should be used purely for comfort for the user not having to submit the page when there's something Javascript can validate against
For any further PHP validation messages, you can either pass variables into GET or SESSION, eg.
<?php
session_start();
if (count($_POST)) {
if (!/* Condition 1 */) $_SESSION['error'] = "Message";
if (!isset($_SESSION['error'])) {
// Proceed
} else header("Location: script.php");
}
?>
On the page:
<?php if (isset($_SESSION['errir'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
} ?>
Since your code sample is PHP-code, it seems that you are posting the form and validate it server-side, and then you show an alert if any field is empty? In that case, the page has already reloaded, before the alertbox is shown. You are mixing server-side and client-side code.
If you want to show an alert box if the user hasn't filled in all the fields (without reloading the page), you will have to do the validation with JavaScript. You should still keep your PHP-validation as well though!
If you use jQuery for instance, you could do something like this:
$("#your-form-id").submit(function(){
// Check all your fields here
if ($("#input-field-1").val() === "" || $("#input-field-2").val() === "")
{
alert("Please fill out all fields");
return false;
}
});
It can of course be done without jQuery as well. In that case you can use the onsubmit attribute of the form tag to call a JavaScript function when the form is posted, and within that function you do the validation of the form, show an alert box if any field is empty, and then return false from the function to prevent the form from being posted to the server.

PHP: submit form with self and render different page items?

I've never done that before and simply need a little advice how to do so …
I have a index.php file with a simple contact form.
<form id="contactform" method="post" action="<?php echo $_SERVER["SCRIPT_NAME"] ?>">
The index.php file has the following script on top.
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<?php
//Vars
$Name = Trim(stripslashes($_POST['author']));
$EmailFrom = Trim(stripslashes($_POST['email']));
$Subject = Trim(stripslashes($_POST['subject']));
$Type = Trim(stripslashes($_POST['type']));
$Comment = Trim(stripslashes($_POST['message']));
$EmailTo = "address#something.com";
//Validation
$valid = true;
if ( $Name == "" ) $valid = false;
if ( isValidEmail( $EmailFrom ) == 0 ) $valid = false;
if ($Subject == "") $valid = false;
if ($Comment == "") $valid = false;
function isValidEmail( $email = null ) {
return preg_match( "/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*#[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix", $email );
}
//Body
$Body = $Type;
$Body .= "\n\n";
$Body .= $Comment;
//Headers
$email_header = "From: " . $EmailFrom . "\r\n";
$email_header .= "Content-Type: text/plain; charset=UTF-8\r\n";
$email_header .= "Reply-To: " . $EmailFrom . " \r\n";
//Send
if ($valid)
$success = mail($EmailTo, $Subject, $Body, $email_header);
?>
I have two questions now:
1.)
How exactly can I render/not-render certain stuff when either the validation went wrong or a success or an error comes back when submitting the mail?
e.g. I know that I can do that!
if ( !$valid )
print "Failed to make contact. Enter valid login credentials! <a href='/#contact' title='try again'>try again?</a>";
if ( $success )
print "Successfully made contact.";
else
print "Failed to make contact. <a href='/#contact' title='try again'>try again?</a>"; */
?>
However $valid will always be wrong on page-load when not submitting the form and also the email will always return the error message on the first page load. How can I only render or not render specific stuff when the form is submitted?
E.g. When submitting the form and a success comes back I don't want to render the #contactform anymore. I simply want to print "Successfully made contact" into an h1 or so.
How can I make that happen? It's probably rather simple I just can't find a solution for myself.
2.)
When using $_SERVER["SCRIPT_NAME"] or PHP_SELF as action the url after submitting the form will always change to "mydomain.com/index.php". Can I prevent that from happening? I want to submit the index.php file itself however I just don't like it when /index.php is written into the url. Is it possible to stop that from happening?
Thank you for your help!
Matt,
For the first question as to printing to the screen based on success or failure of the email, your checks seem fine, but you probably aren't going to get an email failure in time to display that to the screen. That said, you just need to wrap your second set of code in an if statement. Something like this:
if( isset($_POST['Submit']) ){ //only attempt to display if form submitted.
//Your code here
}
As for not including the directory in the form action, there are many ways to do this, but here's one:
$scriptString= explode('/',$_SERVER['SCRIPT_NAME']);
$scriptSize = count($scriptString)-1;
$script = $scriptString[$scriptSize];
And then use $script in the form action.

Categories