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;
}
}
Related
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 :)
I am using the jQuery Form Post plugin from malsup, with the following code:
//Post a form
function PostForm(FormID, Target) {
var $t = Math.round(new Date().getTime() / 1000);
try{
var options = {
target: Target,
beforeSubmit: function () {
jQuery(Target).html('<div id="frmLoadingImageWrapper"><img src="/assets/images/ajax-loader.gif" alt="loading..." height="11" width="16" /></div>');
jQuery(Target).slideDown('slow');
},
success: function (html) {
setTimeout(function () {
jQuery(Target).html(html);
jQuery(FormID)[0].reset();
if($('#captcha-gen').length){
$.get('/inc/captcha.php?_=' + $t, function(data){
$('#captcha-gen').html(data);
});
}
}, 100);
},
error: function(e){
var $html = e.responseText;
jQuery(Target).html($html);
jQuery(Target).slideDown('fast');
if($('#captcha-gen').length){
$.get('/inc/captcha.php?_=' + $t, function(data){
$('#captcha-gen').html(data);
});
}
setTimeout(function() {
jQuery(Target).slideUp('fast');
}, 3500);
}
};
jQuery(FormID).ajaxSubmit(options);
}catch(err){
alert(err.message);
}
}
When I submit my form to /inc/mail.php the actuall PHP code shows in my Target instead of getting processed.
How can I fix this issue? All other PHP scripts work as they should, including other ajax pulled php scripts.
Here is the mailer code, it's using PHP SMTP
<?
require("/inc/class.phpmailer.php");
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('m/d/Y');
$time = date('H:i:s');
//form data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$captcha = $_POST['secAnswer'];
$valid = true;
if(!is_string($email) || !(strlen($email)>0) || !ValidateEmail($email)){
$valid = false;
}
if(!is_string($name) || !(strlen($name)>0) || !ValidateText($name)){
$valid = false;
}
if(!is_string($message) || !(strlen($message)>0) || !ValidateText($message)){
$valid = false;
}
if(!CheckCAPTCHA($captcha)){
$valid = false;
}
sleep(1.5);
if($valid){
$mail = new PHPMailer();
$mail->IsMail(); // send via SMTP
$mail->From = $email; // SMTP username again
$mail->AddAddress("kevin#pirnie.us"); // Your Adress
$mail->Subject = "New mail your site!";
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Body = "<p>You have recieved a new message from the enquiries form on your website.</p>
<p><strong>Name: </strong> {$name} </p>
<p><strong>Email Address: </strong> {$email} </p>
<p><strong>Phone: </strong> {$phone} </p>
<p><strong>Message: </strong> {$message} </p>
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
if(!$mail->Send())
{
echo "Mail Not Sent <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Mail Sent";
}else{
echo "Mail Not Sent. Please make sure all fields are filled out correctly.";
}
function ValidateEmail($str){
$atIndex = strrpos($str, "#");
if (is_bool($atIndex) && !$atIndex){
return false;
}else{
if (filter_var($str, FILTER_VALIDATE_EMAIL)) {
$domain = substr($str, $atIndex + 1);
return (checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"));
}else{
return false;
}
}
}
function ValidateText($str){
return (bool)preg_match("/^[a-zA-Z0-9 _-]+$/", $str);
}
function CheckCAPTCHA($str){
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/captcha.class.php');
$csc = new ResponsiveCaptcha();
if($csc->checkAnswer($str)){
return TRUE;
}else{
return FALSE;
}
}
Make sure that your server supports the short PHP open tag <?
If not : change the short_open_tag value in your php.ini file
or use <?php
I've tested my site's mailing with a different script - just to make sure it wasn't the host, and it's working fine.
I'm not sure why my code isn't working. I've included all my contact forums code except the html. It seems to not be loading the php, as it doesn't show any error messages when I put in an invalid email etc. - it just refreshes the page it seems.
Help is much appreciated, thanks everyone.
<!-- Contact Form Js -->
<script type="text/javascript">
// contact form js
jQuery(document).ready(function($) {
$("#ajax-contact-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "inc/contact-process.php",
data: str,
success: function(msg) {
// Message Sent? Show the 'Thank You' message and hide the form
if(msg == 'OK') {
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
setTimeout("location.reload(true);",7000);
} else {
result = msg;
}
$('#note').html(result);
}
});
return false;
});
});
</script>
<!-- End Contact -->
PHP - 'contact-processes'
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/
*/
include dirname(dirname(__FILE__)).'/config.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'functions.php';
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name)
{
$error .= 'Please enter your name.<br />';
}
// Check email
if(!$email)
{
$error .= 'Please enter an e-mail address.<br />';
}
if($email && !ValidateEmail($email))
{
$error .= 'Please enter a valid e-mail address.<br />';
}
// Check message (length)
if(!$message || strlen($message) < 15)
{
$error .= "Please enter your message. It should have at least 15 characters.<br />";
}
if(!$error)
{
ini_set("sendmail_from", WEBMASTER_EMAIL); // for windows server
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
echo 'OK';
}
}
else
{
echo '<div class="notification_error">'.$error.'</div>';
}
}
?>
PHP - 'functions'
<?php
function ValidateEmail($value)
{
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($value == '') {
return false;
} else {
$string = preg_replace($regex, '', $value);
}
return empty($string) ? true : false;
}
?>
PHP - 'config'
<?php
define("WEBMASTER_EMAIL", 'snip#myemail.com');
?>
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";
}
So I've been spending hours on finding something specific to my issue, but I can't seem to find any.
I'm in the middle of creating a small CMS. My problem is that I don't know how to make a submitted form in a UI dialog to do the action of PHP_SELF inside of the UI dialog. I have a list of user which can be selected by a radio button. There is a delete button which has some javascript attached:
$('#delete_user').on('click', function(e) {
if (id != null ) {
var url = "delete_user.php?id=" + id;
$('#dialog-placeholder').dialog().load(url);
$('.ui-dialog :button').blur();
}
e.preventDefault();
return false;
});
Now, my problem is that I have made it to the UI dialog where i get the ID sent with the url, but I have no idea how to send a form and still keep it in the dialog with the underneath PHP:
<?php
if ((isset($_GET['id'])) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
} elseif ((isset($_POST['id'])) && is_numeric($_POST['id'])) {
$id = $_POST['id'];
} else {
echo "<p>An error has occurred. Please try again.</p>";
echo "Close";
$jQuery_close = <<<msg
<script>
$('.close_dialog').on('click', function(){
location.reload();
dialog("close");
});
</script>
msg;
echo $jQuery_close;
exit();
}
require('includes/db_con.php'); //making a connection to the database
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['sure'] == 'Yes') {
$q = "DELETE FROM users WHERE user_id=$id LIMIT 1";
$r = #mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) {
echo "<p>The user has been deleted</p>";
} else {
echo "<p>The user could not be deleted due to system error. Please try again.</p>";
}
} else {
echo "The user has NOT been deleted!";
}
} else {
$q = "SELECT email, CONCAT(firstname, ' ',lastname) AS name FROM users WHERE user_id='$id'";
$r = #mysqli_query($dbc, $q);
$num = mysqli_num_rows($r);
if ($num = 1) {
while ($row = mysqli_fetch_array($r, MYSQL_ASSOC)) {
echo "<p>Are you sure you want to delete this user?</p>";
echo $row['email'] . '<br />';
echo $row['name'];
}
echo '<form action="' . $_SERVER["PHP_SELF"] . '" method="post">
<input type="HIDDEN" name="id" value="' . $id .'" />
<input type="submit" name="sure" value="Yes" />
<input type="submit" name="sure" value="No" />
</form>';
} else {
echo "This page has been accessed in error";
}
}
mysqli_close($dbc);
?>
When pressing "yes" or "no" in the form, it just directly goes to a new page.
My question is, how do I fire the php and send the form within the dialog?
Place your e.preventDefault() at the start of the delete click handler, not at the end where you currently have it, it should be like this:
$('#delete_user').on('click', function(e) {
e.preventDefault();
if (id != null ) {
var url = "delete_user.php?id=" + id;
$('#dialog-placeholder').dialog().load(url);
$('.ui-dialog :button').blur();
}
return false;
});