I have a simple html form with just a box for the user to enter their email address.
When the "submit" button is pressed I want the email address submitted to be:
(a) emailed to me
(b) automatically added to a Google form
I can do both of these individually. I can perform (a) using:
<form id="input-form" action="email.php" method="POST">
where "email.php" is:
<?php
mail('me#gmail.com', $_POST['email'], "Add to Mailing List");
header('Location: https://my_website.com/thanks.html');
?>
and I do (b) using:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#input-form').on('submit',function(){
var inputq1 = encodeURIComponent($('#email').val());
var q1ID = "entry.1047793221";
var baseURL = 'https://docs.google.com/forms/d/e/1FAIpFLSe7dz1sfyEigQF3QGkTfKCieaqb8OgXoGzLOZPmhn6TvjqFg/formResponse?';
var submitURL = (baseURL + q1ID + "=" + inputq1);
console.log(submitURL);
$(this)[0].action=submitURL;
$('#input-feedback').text('Thank You!');
location.replace("https://my_website.com/thanks.html")
});
</script>
When I comment out the javascript, the submitted information is emailed to me as desired and the user is directed to my "thank you" page. But when I include the javascript, now the email doesn't arrive, but the email address that they entered is instead added to the Google form. So the Google form works part works, but it seems to override the sending of the email to myself.
Additionally, when the javascript is included the user no longer is redirected to my "thank you" page. Instead they are just directed to the Google form thank you page:
How can I get both (a) and (b) to happen after submission please?
You can use ajax to to activate your email.php script:
<script>
$('#input-form').on('submit',function(e){
e.preventDefault(); // this stops the form submit
var inputq1 = encodeURIComponent($('#email').val());
var q1ID = "entry.1047793221";
var baseURL = 'https://docs.google.com/forms/d/e/1FAIpFLSe7dz1sfyEigQF3QGkTfKCieaqb8OgXoGzLOZPmhn6TvjqFg/formResponse?';
var submitURL = (baseURL + q1ID + "=" + inputq1);
console.log(submitURL);
$(this)[0].action=submitURL;
var data = {
// fill with form input values
email: $('#email').val(),
};
// send ajax request to send your email
$.ajax({
url: '/email.php',
type: 'POST',
data: data,
success: function( response ) {
response = JSON.parse( response );
// check if email is sent successfuly and respond appropriately
if (response.status == 'success') {
$('#input-feedback').text('Thank You!');
location.replace("https://my_website.com/thanks.html")
} else {
$('#input-feedback').text('Ooops! Something went wrong.');
}
},
error: function (xhr, status, error) {
console.log( xhr.responseText );
}
});
});
</script>
PHP
<?php
$response = [
'status' => 'error',
];
// validate input values
if (empty($_POST['email'])) { // this is the most basic validation
echo json_encode($response); exit();
}
// check if mail was sent successfuly
if( mail('me#gmail.com', $_POST['email'], "Add to Mailing List") ) {
$response['status'] = 'success';
echo json_encode($response); exit();
}
// if email failed to send
echo json_encode($response); exit();
Related
we're using WordPress for our Website. I was asked to add a function to our newsletter subscription that automatically sends an E-Mail to a specific address that is depending on the selected value of the form. Working fine from code side and on my local host, but when implementing it into the live wordpress system i ran across an error. The Situation :
jQuery.AJAX script posts form data to a file "mail.php" in the wp-content folder. the AJAX success function then submits the original form (because the data also needs to be posted to a provider that manages our newsletter subscriptions). This worked fine on a non-wordpress local host.
After searching through javascript console and firebug i realized that after the script tries to post data to the email.php the server returns a 500 Error as if it didnt allow the post to this file.
I did not register the mail.php or the script in any way but added it to the html code behind the e-mail form. Did i miss something here?
Thanks!
<script>
jQuery(document).ready(function() {
jQuery( "#subscribeform" ).one( "submit", function(event) {
event.preventDefault();
var pFirstName = jQuery("#firstname").val();
var pLastName = jQuery("#name").val();
var pSalutation = jQuery("#salutation").val();
var peMail = jQuery("#email").val();
var pDOB = jQuery("#dob").val();
var pMailTo = jQuery("#shop").val();
var data = {
firstname: pFirstName,
name: pLastName,
salutation: pSalutation,
email: peMail,
dob: pDOB,
mailto: pMailTo
};
$.ajax({
type: "POST",
url: "/cms/mail.php",
data: data,
success: function(){
jQuery('#subscribeform').attr('action', "theExternalProviderURL").submit();
}
});
});
});
</script>
mail.php
<?php
include_once '/cms/phpmailer/PHPMailerAutoload.php';
if($_POST){
$shopname = $_POST['mailto'];
$salutation = $_POST['salutation'];
$firstname = $_POST['firstname'];
$name = $_POST['name'];
$email = $_POST['email'];
$dateofbirth = $_POST['dob'];
$recipient = $_POST['mailto'];
switch ($recipient) {
case "Value1":
$recipient = "mail1#mail.com";
break;
case "Value2":
$recipient = "mail2#mail.com";
break;
default:
$recipient = "admin#mail.com";
}
$oMailer = new PHPMailer;
$oMailer->CharSet = 'UTF-8';
$oMailer->isSMTP();
$oMailer->Host = 'mail.host.com';
$oMailer->Username = 'xxx';
$oMailer->Password = 'xxx';
$oMailer->SMTPAuth = true;
$oMailer->SMTPSecure = 'tls';
$oMailer->Port = 587;
$oMailer->From = 'email#email.com';
$oMailer->FromName = 'From Email';
$oMailer->addAddress('adress#adress.com');
$oMailer->isHTML( true );
$oMailer->Subject = 'E-Mail Subject';
$oMailer->Body = 'Text Text Text';
$oMailer->AltBody = strip_tags( $oMailer->Body );
$oMailer->SMTPDebug = 2;
if ( !$oMailer->send() ) {
echo "Error sending Mail: " . $oMailer->ErrorInfo;
exit;
}
echo 'Successfully sent mail to ' . $recipient . ' Shop';
}
?>
As mentioned earlier, HTTP 500 comes from problem in your server/mail.php code. Moreover, there is a special hook to work with ajax requests in WP, see here: https://codex.wordpress.org/AJAX_in_Plugins
What you need is something like:
var data = {data:yourdata, action: "yourajaxaction"};
$.post(ajaxurl,{data: data});
and
add_action( 'wp_ajax_yourajaxaction', 'your_action' );
function your_action() {
include "mail.php";
}
I have this jquery ajax script
$.ajax({
type: "POST",
url: "register.php",
data: "name=" + name + "&email=" + email + "&password=" + password + "&confirm_password=" + confirm_password + "&captcha=" + captcha,
success: function(data){
if(data == "Success"){
$("#tombol_submit").remove();
$("#register_sukses").fadeIn(500);
}else{
$("#register_gagal").html(data).fadeIn(500);
$("#submit").removeAttr("disabled").attr("value", "Submit");
}
}
in the register.php, once the data successfully added to database, it will echo the "Success" word, the word Success is appear in the form page, but the button (tombol_submit) not removed, otherwise it back into Submit button (just like in 'else' statement). How to remove the button, so the client cannot click the submit button again?
here's the register.php script
<?php
session_start();
include "config/koneksi.php";
if(!empty($_POST['captcha'])){
if($_POST['captcha'] == $_SESSION['hasil']){
$fullname = $_POST['name'];
$email = $_POST['email'];
$password = md5($_POST['password']);
$queryform = "INSERT INTO register (fullname,email,pass)
VALUES('$fullname','$email','$password')";
if ($hasilform = mysqli_query($konek2, $queryform)) {
echo "Success";
} else {
echo "Failed";
}
} else {
echo "The captcha code is wrong";
}
} else {
echo "The captcha cannot be empty";
}
?>
Normally $().remove() will work.
If you are asking why this if...else... doesn't work and always goes to else, please check the response from your backend to make sure the response is only a "Success" string.
You can try like this
$("#tombol_submit").css("display","none");
use this:
$("#tombol_submit").hide();
i think
id "tombol_submit" is not exit
Check console for error,
then based on error you can fix the problem.
I have managed to get ReCaptcha 2.0 working in my website. However, it's only working when I don't use AJAX and I let the form submit "naturally".
I want to submit the form with the captcha and alert the user with a success note without refreshing the page.
I tried the following code, but it seems like the server doesn't get the user response:
HTML:
<form class="form" action="javascript:void(0)" novalidate>
<!-- all the inputs... -->
<!-- captcha -->
<div class="input-group">
<div class="g-recaptcha" data-sitekey="6LdOPgYTAAAAAE3ltWQGar80KUavaR-JblgPZjDI"></div>
</div>
<div class="errors" id="errors" style="display: none"></div>
<div class="input-group">
<input type="button" value="Send" class="btn-default right" id="submit">
<div class="clear"></div>
</div>
</form>
JS:
$('#submit').click(function(e) {
console.log('clicked submit'); // --> works
var $errors = $('#errors'),
$status = $('#status'),
name = $('#name').val().replace(/<|>/g, ""), // prevent xss
email = $('#email').val().replace(/<|>/g, ""),
msg = $('#message').val().replace(/<|>/g, "");
if (name == '' || email == '' || msg == '') {
valid = false;
errors = "All fields are required.";
}
// pretty sure the problem is here
console.log('captcha response: ' + grecaptcha.getResponse()); // --> captcha response:
if (!errors) {
// hide the errors
$errors.slideUp();
// ajax to the php file to send the mail
$.ajax({
type: "POST",
url: "http://orenurbach.com/assets/sendmail.php",
data: "email=" + email + "&name=" + name + "&msg=" + msg + "&g-recaptcha-response=" + grecaptcha.getResponse()
}).done(function(status) {
if (status == "ok") {
// slide down the "ok" message to the user
$status.text('Thanks! Your message has been sent, and I will contact you soon.');
$status.slideDown();
// clear the form fields
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
});
} else {
$errors.text(errors);
$errors.slideDown();
}
});
PHP:
<?php
// assemble the message from the POST fields
// getting the captcha
$captcha = '';
if (isset($_POST['g-recaptcha-response']))
$captcha = $_POST['g-recaptcha-response'];
echo 'captcha: '.$captcha;
if (!$captcha)
echo 'The captcha has not been checked.';
// handling the captcha and checking if it's ok
$secret = 'MY_SECRET';
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
var_dump($response);
// if the captcha is cleared with google, send the mail and echo ok.
if ($response['success'] != false) {
// send the actual mail
#mail($email_to, $subject, $finalMsg);
// the echo goes back to the ajax, so the user can know if everything is ok
echo 'ok';
} else {
echo 'not ok';
}
?>
The result in the PHP page:
captcha: The captcha has not been checked.array(2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(22) "missing-input-response" } } not ok
Bottom line is, how can I get the input response manually without it automatically going with the rest of the POST data?
Ok, this was pretty silly.
I have done a couple of things wrong:
In the PHP file, all the strings had single quotes on them, and that caused problems.
Throughout the testing, I added multiple printings of things in the PHP file, thus the if (status == "ok") was never working. I did get the emails but did not get any conformation that I did and now I see why.
When I wanted to check what the PHP file was omitting, I simply went to it's address in the URL and always got an error. Even when the mails were sent. Now I understand that that is not the correct way of checking the logs.
Thanks to #Samurai who helped my figure out things.
Final PHP code:
<?php
// assemble the message from the POST fields
// getting the captcha
$captcha = "";
if (isset($_POST["g-recaptcha-response"]))
$captcha = $_POST["g-recaptcha-response"];
if (!$captcha)
echo "not ok";
// handling the captcha and checking if it's ok
$secret = "MY_SECRET";
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true);
// if the captcha is cleared with google, send the mail and echo ok.
if ($response["success"] != false) {
// send the actual mail
#mail($email_to, $subject, $finalMsg);
// the echo goes back to the ajax, so the user can know if everything is ok
echo "ok";
} else {
echo "not ok";
}
?>
My page doesn't refresh when there are no errors.
I used:
window.location.reload(true);
That is supposed to be executed when data.success returns True.
I'm new to PHP and AJAX, so I'm using this as a guide. I know how to process info to server, but I want to display messages without leaving the page.
PHP:
<?php
// connects to "ajax" database
mysql_connect("localhost", "root", "password");
mysql_select_db("ajax");
// assigns variables to fields
$name = $_POST['name'];
$email = $_POST['email'];
$superheroAlias = $_POST['superheroAlias'];
$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['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['superheroAlias']))
$errors['superheroAlias'] = 'Superhero alias 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 {
$sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
$query = #mysql_query($sql);
header("location: /");
}
// return all our data to an AJAX call
echo json_encode($data);
?>
JS
// magic.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'superheroAlias' : $('input[name=superheroAlias]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true,
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if (!data.success) {
// handle errors for name ---------------
if (data.errors.name) {
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#name-group').append('<div class="help-block">' + data.errors.name + '</div>'); // add the actual error message under our input
}
// handle errors for email ---------------
if (data.errors.email) {
$('#email-group').addClass('has-error'); // add the error class to show red input
$('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
}
// handle errors for superhero alias ---------------
if (data.errors.superheroAlias) {
$('#superhero-group').addClass('has-error'); // add the error class to show red input
$('#superhero-group').append('<div class="help-block">' + data.errors.superheroAlias + '</div>'); // add the actual error message under our input
}
} else {
window.location.reload(true);
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
There are many errors in your code. To begin with, the reason your AJAX call is only executed when there are errors is because you're relocating your page when there aren't any errors.
header("location: /");
Is your culprit. You're relocating the page before you can ever output any JSON. Second of all, your $data variable doesn't contain the [success] key when there is a successful $_POST transit. So even if you weren't to relocate, you still wouldn't be outputting any useful data. Third of all, you never saved a link to your MySQL database, you only instantiated it. Also, you're going to want to use mysqli_ because mysql_ is deprecated.
Change those first two lines of code to this:
$link = new mysqli( "localhost", "root", "password", "ajax" );
Change that if-statement to this:
if ( ! empty( $errors ) ) {
$data["errors"] = $errors;
$data["success"] = false;
} else {
$data["success"] = true;
$data["errors"] = $errors; // There are none, so this isn't neccessary
$sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
$link->query( $sql );
}
By the way, I hope this is for demonstration purposes only, because that is some terrible validation/sanitation. If it isn't, here are some useful links:
http://www.phpro.org/tutorials/Validating-User-Input.html -- In-depth tutorial on sanitation/validation
http://php.net/manual/en/book.mysqli.php -- Your guide to the MySQLi library.
remove header("location: /"); from your php file in else part.
I think this will redirect page so, your response is not like you want.
Here If condition fails then check for $data in else and remove header from else.
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
$sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
$query = #mysql_query($sql);
$data['success'] = false;
//header("location: /");
}
// return all our data to an AJAX call
echo json_encode($data);
Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.