ajax jquery form stopped sending emails - javascript

I have a form which was sending emails from the server before but all of a sudden it stopped working. I cant seem to figure out the issue. When I use the form without ajax then email works perfectly. I saw http 200 code in the dev tools and no errors. Any help would be much appreciated. Thank you.
html:
<form id="form1" class="form-action" action="" method="POST">
<input type="text" name="name" id="name" class = "name" required />
<input type="email" name="email" id="email" required />
<input type="text" name='company' id="company" class="company" required />
<textarea class= "message" name="message" id="message" required />
</textarea>
<script src="https://www.google.com/recaptcha/api.js"></script>
<div class="g-recaptcha" data-sitekey="x" data-callback="recaptcha"></div>
<button type="submit" id="submit-button">Submit</button>
<span class="success_message font-weight-bolder text-center hide" style="margin-left: 30px;">
message received.</span>
</form>
<script>
function reset_form(){
$("#form1")[0].reset();
}
function reset_success_message(){
$('.success_message').addClass('hide');
}
$(document).ready(function(){
$('#name').click(function () {
$('.success_message').addClass('hide');
});
$('.email').click(function () {
$('.success_message').addClass('hide');
});
$('.company').click(function () {
$('.success_message').addClass('hide');
});
$('#message').click(function () {
$('.success_message').addClass('hide');
});
$('#form1').submit(function (e) {
$('.success_message').addClass('hide');
e.preventDefault();
$.ajax({
url: 'serverside.php',
type: 'post',
data: $('#form1').serialize(),
success: function (response) {
if(response == 'submitted'){
reset_form();
$('.success_message').removeClass('hide');
}
}
});
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
serverside.php
<?php
$email_to = 'x#domain.com';
$email_subject = 'form submission';
$email = $_POST ['email'];
$required = array('name','email','company', 'message');
$form1_complete = FALSE;
$validation = array();
if(!empty($_POST)) {
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
foreach($required as $field) {
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
if($_POST[$field] == '') array_push($validation, $field);
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
if(count($validation) == 0) {
$email_content = 'New Comment: ' . "\n\n";
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n\n ";
}
$recaptcha_secret = "x";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true) {
mail($email_to, $email_subject, $email_content, "From:" . $email);
}
else
{
}
echo 'submitted';
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>

You seem to be missing the Recaptcha secrets. Removing the Recaptcha if condition it works fine.
<?php
$email_to = 'ahmed_rises#hotmail.com'; //-----------> Invalid Email Id was added here
$email_subject = 'form submission';
$email = $_POST ['email'];
$required = array('name','email','company', 'message');
$form1_complete = FALSE;
$validation = array();
if(!empty($_POST)) {
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
foreach($required as $field) {
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
if($_POST[$field] == '') array_push($validation, $field);
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
if(count($validation) == 0) {
$email_content = 'New Comment: ' . "\n\n";
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n\n ";
}
//Recaptca Secrets are Missing?????? Random string passed!
$recaptcha_secret = "x";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret="
.$recaptcha_secret."&response=".$_POST['g-recaptcha-response']); //-----> Also Recapta response from
//the form is also missing since there its not working and neither getting passed
$response = json_decode($response, true);
//Printed the Output in which it shows the recapta Error
echo "<pre>";
print_r($response);
//If you ae to remove the Recapta Condition, the mail will be send!
// if($response["success"] === true) {
echo "==========";
echo "email_subject:".$email_subject.", email:".$email.",email_to:".$email_to;
mail($email_to, $email_subject, $email_content, "From:" . $email);
echo "==========";
// }
// else
// {
// echo "Failed";
// }
echo "<br>";
echo 'submitted';
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
Hope it helps :)

Related

Login redirect using jquery

i'll be glad if anyone can help out am working on a login system using jquery but i encounter a problem
what i want to achieve is user filling out their details on the login page and i'll process it using jQuery at the back end without reloading the page, i have achive that but the problem now is when the details they provide and the details in the database is correct i want to redirect them to another page
here is my login form
<form class="form-login" id="loginmyForm" method="post">
<input class="input input_auth" type="text" name="loginemail" id="loginemail" placeholder="E-mail" required />
<span id="loginError_username" class="error error-opacit"></span>
<input class="input input_auth" type="password" name="loginpassword" id="loginpassword" placeholder="Password" required />
<span id="loginError_password" class="error error-opacit"></span>
<input type="hidden" name="source" value="login" id="source">
<button class="btn pulse input_auth" type="button" id="submitFormData" onclick="loginSubmitFormData();" value="Submit">Login</button>
<div class="forgot-password">
<a id="forgotPass" href="#" class="link-btn open-modal" data-openModal="modal-recovery">Forgot your password?</a>
</div>
Here is jquery code
<script type="text/javascript">
function loginSubmitFormData() {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
var source = $("#source").val();
$.post("authlogin.php", { loginemail: loginemail, loginpassword: loginpassword },
function(data) {
$('#loginresults').html(data);
$('#loginmyForm')[0].reset();
});
}
</script>
And here is the login authentication authlogin.php
<?php
session_start();
include 'config/info.php';
// get the details from form
$email=$_POST['loginemail'];
$password = stripslashes($_REQUEST['loginpassword']);
$password = mysqli_real_escape_string($conn,$password);
$sql="SELECT * FROM user_info WHERE email='".$email."'";
$result = mysqli_query($conn,$sql);
$Countrow = mysqli_num_rows($result);
if ($Countrow == 1) {
$fetchrow = mysqli_fetch_assoc($result);
$loginpassword = $fetchrow['password'];
// Verify the password here
if (password_verify($password, $loginpassword)) {
$_SESSION['email'] = $email;
//setcookie('username', $adminID, time() + (86400 * 30), "/");
$date = date('Y-m-d H:i:s');
$ActivityStmt = "INSERT INTO login_activity (`email`, `last_login`, `browser`, `os`, `ip_address`) VALUES('".$email."', '".$date."', '".$gen_userBrowser."', '".$gen_userOS."', '".$gen_userIP."')";
$ActivityResult = mysqli_query($conn, $ActivityStmt);
echo 'Login Successfully! Click to proceed';
exit();
}
else{
echo 'Incorrect Password';
exit();
}
}
else{
echo 'User does not exit';
exit();
}
?>
I have tried using
header('Location: account');
and
window.location.href = "account";
after the session is saved but none is working, please who can help me on how to get this done
You should try this jQuery Code and PHP Code by replacing them in your code section, It will definitely work for you:
<script type="text/javascript">
function loginSubmitFormData() {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
var source = $("#source").val();
$.post("authlogin.php", { loginemail: loginemail, loginpassword: loginpassword },
function(data) {
var data = jQuery.parseJSON( data );
console.log(data);
$('#loginresults').html(data.message);
if(data.redirect_url){
window.location.href = data.redirect_url;
}
$('#loginmyForm')[0].reset();
});
}
</script>
<?php
session_start();
include 'config/info.php';
// get the details from form
$email=$_POST['loginemail'];
$password = stripslashes($_REQUEST['loginpassword']);
$password = mysqli_real_escape_string($conn,$password);
$sql="SELECT * FROM user_info WHERE email='".$email."'";
$result = mysqli_query($conn,$sql);
$Countrow = mysqli_num_rows($result);
if ($Countrow == 1) {
$fetchrow = mysqli_fetch_assoc($result);
$loginpassword = $fetchrow['password'];
// Verify the password here
if (password_verify($password, $loginpassword)) {
$_SESSION['email'] = $email;
//setcookie('username', $adminID, time() + (86400 * 30), "/");
$date = date('Y-m-d H:i:s');
$ActivityStmt = "INSERT INTO login_activity (`email`, `last_login`, `browser`, `os`, `ip_address`) VALUES('".$email."', '".$date."', '".$gen_userBrowser."', '".$gen_userOS."', '".$gen_userIP."')";
$ActivityResult = mysqli_query($conn, $ActivityStmt);
$message = 'Login Successfully!';
$response = array(
'message' => $message,
'redirect_url' => 'https://www.example.com',
);
exit();
}
else{
$message = 'Incorrect Password';
$response = array(
'message' => $message
);
exit();
}
}
else{
$message = 'User does not exit';
$response = array(
'message' => $message,
);
exit();
}
echo json_encode( $response);
?>

Ajax email Availability check with php not working

I want to check email availability but it's not working. and also I am new to javascript and ajax please help me.
his is my code
email input with span to show output(for now there is no output)
<input class="input--style-4" id="email" type="email" name="email" required>
<span id="user-availability-status"></span>
JS
<script>
$(document).ready(function() {
$('#email').blur(function() {
var email = $(this).val();
$.ajax({
url: 'includes\emailAvailability.php',
method: "POST",
data: {
email_val: email
},
success: function(data) {
if (data != 0) {
$('#user-availability-status').html('<span>Username blah not available</span>');
$('#register').attr("disabled", true);
} else {
$('#user-availability-status').html('<span>Username blah Available</span>');
$('#register').attr("disabled", false);
}
}
})
});
});
</script>
PHP file
<?php
if (isset($_POST["email_val"])) {
include("DbConn.php");
$email = mysqli_real_escape_string($conn, $_POST["email_val"]);
$query = "SELECT * FROM customer WHERE email = '" . $email . "'";
$result = mysqli_query($conn, $query);
echo mysqli_num_rows($result);
}
You should check link I refered in comment its your complete answer.
here is a Simple example with your code.
include("DbConn.php");
// Set alerts as array
$error = "";
// I should just trrim and let you check if email is empty .lol
if (empty($_POST["email_val"])) {
$error .= "<p class='error'>Fill email value.</p>";
//Check if this is a real email
} elseif(!filter_var($_POST["email_val"],FILTER_VALIDATE_EMAIL)){
$error .= "<p class='error'>Wrong email type.</p>";
}else{
$email = mysqli_real_escape_string($conn, $_POST["email_val"]);
//You should use prepare statement $email, Shame on you .lol
$query = "SELECT * FROM customer WHERE email = '{$email}'");
$result = mysqli_query($conn, $query);
echo mysqli_num_rows($result);
$error .= "ok";
}
$data = array(
'error' => $error
);
This Jquery :
$(document).ready(function(){
$('#myform').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"includes\emailAvailability.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data.error === 'ok'){
$('#result').html(data.error);
} else {
$('#result').html(data.error);
$('#myform')[0].reset();
}
}
});
});
});
And Html :
<form id="myform">
<input class="input--style-4" id="email" type="email" name="email_val">
<span id="result"></span>
<button type="button" class="btn btn-primary">Send</button>
</form>
you can use type:"POST" instead of method:"POST" I think work thanks

rsvp form in a WordPress Widget: submits twice, why?

I'm creating a custom WordPress widget that contains a rsvp form. When submited the form sends 2 emails, one to the organizer, one to the guest.
My problem: both email are sent twice (twice to the organizer, twice to the guest). What is wrong in my code?
The code is similar to this:
function widget($args, $instance)
{
//init my vars here
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$raw_datas = $_POST["widget-my_widget_name"];
if (!empty($raw_datas)) {
//this fct treats form data
$rsvpdata = nd_manage_rsvp($raw_datas);
if ($rsvpdata['status'] == 'success') {
//init $to, $subject, $message, $headers according to $rsvpdata
$sent = wp_mail( $to, $subject, $message, $headers, $attachments );
$sent2 = wp_mail( $to2, $subject2, $message2, $headers2, $attachments2 );
if(!($sent === true && $sent2 === true)) {
//failure notice here
$rsvpdata['status'] = 'failure';
} else {
//reinit my vars here
$rsvpdata['status'] = 'sent';
}
}
}
} ?>
<div class="description-text">
<form id="<?php echo $this->get_field_id('rsvp-form'); ?>" name="<?php echo $this->get_field_name('rsvp-form'); ?>" action="#<?php echo $this->id; ?>" method="post" onsubmit="return validate(<?php echo '\'' . $this->id . '\''; ?>)">
//some form inputs here
<input class="rsvp-submit mybutton" type="submit" value="<?php _e('Send','textdomain');?>">
</form>
</div>
<?php
}
Edit: my JS function "validate" is only validation, there is no ajax to handle form:
//validate rsvp form values
function validate(formid) {
var attends = jQuery("#widget-"+formid+"-attend_yes");
var events = jQuery("#widget-"+formid+"-events_check");
var minOneCB = jQuery('#'+formid+' input:checkbox').is(':checked');
var CName = jQuery("#widget-"+formid+"-name");
var CEmail = jQuery("#widget-"+formid+"-email");
CName.tipsy({trigger: 'manual', title: 'data-tipsy', offset: 1});
CEmail.tipsy({trigger: 'manual', title: 'data-tipsy', offset: 1});
events.tipsy({trigger: 'manual', title: 'data-tipsy', offset: 5});
events.tipsy("hide");
CName.tipsy("hide");
CEmail.tipsy("hide");
jQuery(document).on('click', function(event) {
if (!jQuery(event.target).closest('.rsvp-submit').length) {
events.tipsy("hide");
CName.tipsy("hide");
CEmail.tipsy("hide");
}
});
if (attends.is(':checked') && !minOneCB){
events.tipsy("show");
return false;
}
if(CName.val() == ''){
CName.tipsy("show");
return false;
}
//isEmail is a function that check if email is valid
if(CEmail.val() == '' || !isEmail(CEmail.val()) ){
CEmail.tipsy("show");
return false;
}
}

check php variable in javascript function

I've downloaded a template for web.
In this template, there is a php script to send email. In this script there is a validate() function, in which there is a variable $return_array. one of its value is $return_array['success'] that could be '0' or '1'. In another file, a javascript one, there is a click() function, that manages the value of 'success' in the php script doing if(html.success == '1')...but it does not work as expected, infact it is always '0'...what do I need to check?
Here is the html form:
<form method="POST" action="send_form_email.php" id="contactform">
<div>
<label for="name" style="color:white;">Inserisci il tuo nome</label>
<input type="text" class="input-field" id="name" name="name" value="">
</div>
<div>
<label for="email" style="color:white;">Inserisci la tua e-mail</label>
<input type="text" class="input-field" id="email" name="email" value="">
</div>
<div>
<label style="color:white;">Scrivi il tuo messaggio</label>
<textarea id="message" name="message" style="min-height: 160px;"></textarea>
</div>
<a id="button-send" href="#" title="Send Email" class="button" style="width:100%;">Invia E-Mail</a>
<div id="success">Il tuo messaggio &egrave stato inviato correttamente!</div>
<div id="error">Impossibile inviare il messaggio. Riprovare pi&ugrave tardi.</div>
</form>
and here is the function into the php
<?php
// EDIT THE 2 LINES BELOW AS REQUIRED
$send_email_to = "mail.address#email.com";
$email_subject = "Feedback subject";
function send_email($name,$email,$email_message)
{
global $send_email_to;
global $email_subject;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$email. "\r\n";
$message = "<strong>Email = </strong>".$email."<br>";
$message .= "<strong>Name = </strong>".$name."<br>";
$message .= "<strong>Message = </strong>".$email_message."<br>";
#mail($send_email_to, $email_subject, $message,$headers);
return true;
}
function validate($name,$email,$message)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['name_msg'] = '';
$return_array['email_msg'] = '';
$return_array['message_msg'] = '';
if($email == '')
{
$return_array['success'] = '0';
$return_array['email_msg'] = 'email is required';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$return_array['success'] = '0';
$return_array['email_msg'] = 'enter valid email.';
}
}
if($name == '')
{
$return_array['success'] = '0';
$return_array['name_msg'] = 'name is required';
}
else
{
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp, $name)) {
$return_array['success'] = '0';
$return_array['name_msg'] = 'enter valid name.';
}
}
if($message == '')
{
$return_array['success'] = '0';
$return_array['message_msg'] = 'message is required';
}
else
{
if (strlen($message) < 2) {
$return_array['success'] = '0';
$return_array['message_msg'] = 'enter valid message.';
}
}
return $return_array;
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$return_array = validate($name,$email,$message);
if($return_array['success'] == '1')
{
send_email($name,$email,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
and following the javascript code:
$('#button-send').click(function(event){
$('#button-send').html('Invio in corso...');
event.preventDefault();
//$('html, body').scrollTo( $('#contact'), 'fast' );
$.ajax({
type: 'POST',
url: 'send_form_email.php',
data: $('#contactform').serialize(),
success: function(html) {
if(html.success == '1')
{
$('#button-send').html('Invia E-Mail');
$('#success').show();
}
else
{
$('#button-send').html('Invia E-Mail');
$('#error').show();
console.log(html);
}
},
error: function(){
$('#button-send').html('Invia E-Mail');
$('#error').show();
console.log("not html.success");
}
});
});
EDIT:
I've edited the php part adding at the end the json_encode and content type, but when there is an error, like name missing or mail missing, I expect to see something appears near the input form, but it does not...
Use return json_encode($return_array); Instead of return $return_array;.
Json encode returns key => value pair array .
Also use dataType: "json" OR dataType: "jsonp" in ajax call.

Cleaning my php contact form from captcha

I have some trouble cleaning and making my contact form working.
I'm using a template which had a captcha validation and I don't want it. There was also a "website input that I delete.
I'm a newbie in php so I don't really know what I have to remove and I don't want to start a new php/js files
My contact-send.php file is in a php folder. So I assume the action call in the html is good.
I have two other files in there ( captcha_page.php and image.php but I won't use here, will delete it, so I don't post code )
<form class="contact-form" method="post" action="php/contact-send.php">
<p class="input-block">
<input type="text" name="name" id="name" placeholder="Name *" />
</p>
<p class="input-block">
<input type="email" name="email" id="email" placeholder="Email *" />
</p>
<p class="input-block">
<textarea name="message" id="message" placeholder="Message *"></textarea>
</p>
<p class="input-block">
<button class="button turquoise submit" type="submit" id="submit"><i class="icon-paper-plane"></i></button>
</p>
</form><!--/ .contact-form-->
<?php
if (isset($_REQUEST['action'])) {
if ($_REQUEST['action'] == "contact_form_request") {
$ourMail = "xxx.xxxx#gmail.com";
$required_fields = array("name", "email", "message");
$pre_messagebody_info = "";
$errors = array();
$data = array();
parse_str($_REQUEST['values'], $data);
//check for required and assemble message
if (!empty($data)) {
foreach ($data as $key => $value) {
$name = strtolower(trim($key));
if (in_array($name, $required_fields)) {
if (empty($value)) {
if ($name == "name") {
$errors[$name] = "Please enter your Name before sending the message";
}
if ($name == "message") {
$errors[$name] = "Please enter your message ";
}
if ($name == "email") {
if (!isValidEmail($value)) {
$errors[$name] = "Please enter correct Email address";
}
}
}
}
}
}
session_start();
$verify = $_SESSION['verify'];
if ($verify != md5($data['verify'])) {
$errors["verify"] = "Please enter correctly captcha";
}
$result = array (
"is_errors" => 0,
"info" => ""
);
if (!empty($errors)) {
$result['is_errors'] = 1;
$result['info'] = $errors;
echo json_encode($result);
exit;
}
$pre_messagebody_info .= "<strong>Name</strong>" . ": " . $data['name'] . "<br />";
$pre_messagebody_info .= "<strong>E-mail</strong>" . ": " . $data['email'] . "<br />";
$pre_messagebody_info .= "<strong>Website</strong>" . ": " . $data['website'] . "<br />";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers.= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers.= "From: " . $data['email'] . "\r\n";
$after_message = "\r\n<br />--------------------------------------------------------------------------------------------------\r\n<br /> This mail was sent via contact form";
if (mail($ourMail, "Email from contact form", $pre_messagebody_info .="<strong>Message</strong>" . ": " . nl2br($data['message']) . $after_message, $headers)) {
$result["info"] = "success";
} else {
$result["info"] = "server_fail";
}
echo json_encode($result);
exit;
}
}
function isValidEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
?>
if ($('.contact-form').length) {
var $form = $('.contact-form'),
$loader = '<span>Loader...</span>';
$form.append('<div class="hide contact-form-responce" />');
$form.each(function () {
var $this = $(this),
$response = $('.contact-form-responce', $this).append('<p></p>');
$this.submit(function () {
$response.find('p').html($loader);
var data = {
action: "contact_form_request",
values: $this.serialize()
};
//send data to server
$.post("php/contact-send.php", data, function (response) {
$('.wrong-data', $this).removeClass("wrong-data");
$response.find('span').remove();
response = $.parseJSON(response);
if (response.is_errors) {
var p = $response.find('p');
p.removeClass().addClass("error");
$.each(response.info, function (input_name, input_label) {
$("[name=" + input_name + "]", $this).addClass("wrong-data");
p.append(input_label + '</br>');
});
$response.show(300);
} else {
$response.find('p').removeClass().addClass('success');
if (response.info === 'success') {
$response.find('p').append('Your email has been sent!');
$this.find('input, textarea, select').val('').attr('checked', false);
$response.show(300).delay(2500).hide(400);
}
if (response.info === 'server_fail') {
$response.find('p').append('Server failed. Send later!');
$response.show(300);
}
}
// Scroll to bottom of the form to show respond message
var bottomPosition = $response.offset().top - 50;
if ($(document).scrollTop() < bottomPosition) {
$('html, body').animate({ scrollTop : bottomPosition });
}
});
return false;
});
});
}
sorry, html, php and js are together, didn't manage to make something better...
thanks a lot guys !!!
remi
remove these lines :
$verify = $_SESSION['verify'];
if ($verify != md5($data['verify'])) {
$errors["verify"] = "Please enter correctly captcha";
}

Categories