Ajax/php contact form sending blank emails from time to time - javascript

Well I have this contact form that sends blank emails. But I did some testing and it doesn't happens to me. The only way this could happen, I think, would be by accesing the .php file directly. If not I don't know what could be the problem. The form doesn't let you send a blank email. If this keeps happening I'm going to add a validation in the php file too, but until I find out what is the problem I don't want to ignore this messages.
This is the HTML
<form name="contactForm" id="contactForm" method="post" action="/contactEngine.php" onsubmit="return validateForm()">
<input title="Input name" type="text" name="Name" id="Name" placeholder="Nombre:" required="">
<input title="Input email" placeholder="Email:" type="email" name="Email" id="Email" required="">
<input type="text" placeholder="Subject:" name="Subjet" id="Subjet">
<textarea title="Input message" placeholder="Mensaje:" name="Message" rows="20" cols="20" id="Message" required=""></textarea>
<input title="Input result" placeholder="25 + 25 = ?" type="text" name="Captcha" id="Captcha" required="">
<p id="wrongCaptcha"> Try again </p>
<input type="submit" name="submit" value="send" class="submit-button">
</form>
This is the JS
function validateForm(e) {
e.preventDefault();
var x = document.forms["contactForm"]["Captcha"].value;
if (x != 50) {//if captcha is wrong
$("#Captcha").addClass("wrongCaptchaEntered");
$("#Captcha").css("animation-name" , "none");
setTimeout (function(){
$("#Captcha").css("animation-name" , "changeBorder");
},100);
if ($("#wrongCaptcha").css("display") == "none"){
$("#wrongCaptcha").slideDown();
}
}
else { //if captcha is correct
var formAction = $("#contactForm").attr("action");
if (formAction == "/contactEngine.php"){
var formData = $("#contactForm").serialize();
$.post( formAction, formData, function(data){
console.log (data);
$(".formulario").changeTo({content: "<h2 class='section-title BackgroundGradientBlack'>"+ data +"</h2>"});
});
}
}
return false;
}
And the PHP
<?php
$EmailFrom = "EmailFrom#test.com";
$EmailTo = "EmailTo#test.com";
$Name = Trim(stripslashes($_POST['Name']));
$Email = Trim(stripslashes($_POST['Email']));
$Subject = Trim(stripslashes($_POST['Subjet']));
$Message = Trim(stripslashes($_POST['Message']));
$email_content = "Frontpage";
$email_content .= "\nNombre: $Name";
$email_content .= "\nEmail: $Email";
$email_content .= "\nMotivo: $Subject";
$email_content .= "\nMensaje: $Message";
$email_headers = "From: <$EmailFrom>";
if (mail($EmailTo, $Subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Mensaje enviado";
} else {
http_response_code(500);
echo "Error";
}
?>
Thanks!

Probably some bot that's testing the PHP endpoint it can see in your JS and is sending data to it, trying to cause havoc. I bet if you logged the $_POST variable every time an email was sent, you'd seen a lot of spammy nonsense in some $_POST variables. Emails are blank just because the bots aren't smart enough to know which keys to use in its POSTs.

Related

Contact form that doesn't refresh page on submit while using Wordpress

I have setup the following code to make a contact form that doesn't refresh the page when submitted.
HTML:
<form method="POST" id="contact-form">
<div class="contact-element flex-row">
<input class="" type="text" name="name" placeholder="Name" id="name" Required>
<input class="" type="text" name="email" placeholder="Email Address" id="email" Required>
</div>
<input class="" type="text" name="subject" placeholder="Subject" id="subject" Required>
<textarea type="text" name="message" rows="5" placeholder="Message" id="message" Required></textarea>
<input class="contact-submit" id="submit" name="submit" type="submit" value="Submit">
<input type="hidden" name="action" value="form-action">
</form>
JavaScript/AJAX request:
$("#contact-form").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = "<?php echo get_template_directory_uri(); ?>/library/contact-form.php";
var posting = $.post( url, {
name: $('#name').val(),
email: $('#email').val(),
subject: $('#subject').val(),
message: $('#message').val(),
});
posting.done(function( data ) {
alert('success');
});
});
PHP:
// Set $to as the email you want to send the test to.
$to = "my#email.com";
// Email subject and body text.
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$headers .= "Reply-To: ". strip_tags($_POST['email']) . "\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = $_POST["message"];
// send test message using wp_mail function.
if(isset(($_POST['name']), ($_POST['email']), ($_POST['message']), ($_POST["subject"]))) {
$sent_message = wp_mail( $to, $subject, $message, $headers );
} else {
};
//display message based on the result.
if ( $sent_message ) {
// The message was sent.
echo 'The test message was sent. Check your email inbox.';
} else {
// The message was not sent.
echo 'The message was not sent!';
}
The code works when I run it on my local website, It returns the success alert.
The PHP code also succeeds in sending the contact form information to my email address.
I get a 'the server responded with a status of 500 (internal error)' when I run it on my web server.
I think I must have overlooked something stupid here but I can't see it and hoping someone else can see it and help me out?
Thanks in advance!
This is how i do my ajax submission for a form. It's contains WordPress security measures, you can learn them from google in detail but small description will be provided by me.
HTML
<form method="POST" id="contact-form">
<div class="contact-element flex-row">
<input class="" type="text" name="name" placeholder="Name" id="name" Required>
<input class="" type="text" name="email" placeholder="Email Address" id="email" Required>
</div>
<input class="" type="text" name="subject" placeholder="Subject" id="subject" Required>
<textarea type="text" name="message" rows="5" placeholder="Message" id="message" Required></textarea>
<input class="contact-submit" id="submit" name="submit" type="submit" value="Submit">
<input type="hidden" name="action" value="contact_form" id="cf_action" url="<?= admin_url('admin-ajax.php'); ?>">
<?php wp_nonce_field( 'contact_form', 'contact_form_wpnonce' ); ?>
</form>
Javascript
jQuery(function($){
$("#contact-form").submit(function(e){
var url = $('#cf_action').attr('url');
$.ajax({
type: "POST",
url: url,
data: $("#contact-form").serialize(),
success: function(data) {
alert(data.data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
Function
add_action('wp_ajax_contact_form', 'contact_form_function');
add_action('wp_ajax_nopriv_contact_form', 'contact_form_function');
function contact_form_function()
{
if ( !isset($_POST['xyz_contact_email_meta_box_nonce']) && !wp_verify_nonce($_POST['xyz_contact_email_meta_box_nonce'], 'xyz_save_contact_email_data')) {
# code...
return;
}
$user_name = sanitize_text_field( $_POST['name'] );
$user_email = sanitize_email( $_POST['email'] );
$user_subject = sanitize_text_field( $_POST['subject'] );
$user_message = sanitize_textarea_field( $_POST['message'] );
$to = 'xyz#gmail.com';
$subject = $user_subject;
$body = 'Hi you recived a message from '.$user_name.'('.$user_email.'),<p>'.$user_message.'</p>';
$headers = array('Content-Type: text/html; charset=UTF-8');
$status = wp_mail( $to, $subject, $body, $headers );
if($status){
wp_send_json_success('sent successful');
}else{
wp_send_json_error('something went wrong');
}
}
Description
okay let me guide through WordPress a bit.
WordPress have already inbuilt functionality to handle ajax-request from it's theme's functions.php, you have to copy and paste html code where you want form to show, js code in footer and function code in functions.php
Here are some tips:-
wp_nonce_field = it's used for security purpose and prevent hackers to use form for different purpose.
Sanitize data to make sure you are not receiving any malicious code from your posted data, you can use esc_attr(it will convert any tags and script into html) too.
It's a good habit to send data back with WordPress default function wp_send_json_success & wp_send_json_error.
(Forgive me if you feel hard to understand since it's my first answer on stackoverflow)
Cheers!!

How to redirect on button click using php

I am using a button on my form. I am trying to redirect to another page on button click after successful submission of user info. Every thing works properly except redirection. Here is the code I tried.
Html code:
<form role="form" id="contact-form" method="get">
<div class="form-group row">
<input type="email" id="email" name="email" placeholder="Enter your email" required="required" class="form-control input-lg" />
<input type="text" id="address" name="address" placeholder="Enter your address" required="required" class="form-control input-lg" />
<button type="submit" class="btn btn-t-primary">Show Me Now!</button>
</div>
</form>
Javascript code:
function contact() {
$("#contact-us-form").submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
form = $(this);
data = $(this).serialize();
$.post("contact.php", data, function(response){
form.trigger('reset');
});
}
Php code:
<?php
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
if (isset($_POST['email'])) {
$email = $_POST['email'];
$address= $_POST['address'];
$subject = "Message from: ".$email;
$content = "Email: " . $email."\n"
. "Address: " . $address;
$headers ='Reply-To: ' . $email . "\r\n";
mail('example#gmail.com', $subject ,$content, $headers );
header("Location:https://www.example.com");
echo 1;
}else {
echo 0;
}
?>
You can't redirect an ajax request from PHP, instead use this:
$(function() {
$("#contact-form").submit(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
form = $(this);
data = $(this).serialize();
$.post("contact.php", data, function(response) {
form.trigger('reset');
//Redirection
window.location.href = "https://www.google.com";
});
});
});
Just remove this header("Location:https://www.example.com"); from your PHP.
I hope this will help you.
Maybe you have to write the entire url when you are setting the header:
header("Location: http://www.google.com");
This isn't actually necessary.
Inside of the HTML form tag, add where you want to post the data to inside of the action attribute.
<form role="form" id="contact-form" method="get" action="postpage.php"> <!-- notice the action attribute !-->
Try this!
echo '<meta http-equiv=REFRESH CONTENT=0;url=./yourDestination.php>';
As we can see in the code, the page would refresh to the url you declared.
"Content = 0" means that it'll refresh after 0 seconds
You could modify the number if you want!
I wonder why you have set form method="get", but used $_POST variable under php code. Here's another version using POST method, try if it helps.
<?php
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
if (isset($_POST['email'])) {
$email = $_POST['email'];
$address= $_POST['address'];
$subject = "Message from: ".$email;
$content = "Email: " . $email."\n"
. "Address: " . $address;
$headers ='Reply-To: ' . $email . "\r\n";
mail('example#gmail.com', $subject ,$content, $headers );
header("location: https://google.com");
exit;
}
?>
<form role="form" id="contact-form" method="post">
<div class="form-group row">
<input type="email" id="email" name="email" placeholder="Enter your email" required="required" class="form-control input-lg" />
<input type="text" id="address" name="address" placeholder="Enter your address" required="required" class="form-control input-lg" />
<button type="submit" class="btn btn-t-primary">Show Me Now!</button>
</div>
</form>
You need to set the absolute address, including the protocol (https://) in your header location if you want to redirect to a new site.
header("Location: https://www.google.com")
Without the protocol, the location is assumed to be relative and will be appended to the existing domain.
Additionally, you should not echo anything after the headers.
First you have to write PHP code that handles Ajax Request:
if (isset($_POST['ajax_request'])) {
// write code;
echo "http://www.example.com"; // redirect url
}
Javascript:
jQuery(document).ready(function($) {
$.post('/path/to/file.php', {"ajax_request": true}, function(data, textStatus, xhr) {
window.location.href = data; // http://www.example.com
});
});
Hope this helps.

PHP contact form will just refresh the page after submission.

After searching for about 3 hours i still can't figure this one out.
I Have a html template with a contact form and im trying to make it work using a PHP script.
I changed the template to PHP and pasted the PHP form script in it. everything is working fine except the confirmation text.
After a successful submission it will just refresh the page instead of printing "Your mail has been sent successfuly ! Thank you for your feedback". i do not want a redirect, i just want it to print on the same page.
Any ideas?
I got a sample of my code.
<form action="<? echo $_SERVER['PHP_SELF']; ?>" id="contact-form" method="post" class="form afsana-form" role="form">
<div class="row">
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="name" name="name" placeholder="name" type="text" required autofocus />
</div>
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="email" name="email" placeholder="email" type="email" required />
</div>
<div class="col-sm-12 form-group">
<textarea class="form-control" id="message" name="message" placeholder="message" rows="5"></textarea>
</div>
<div class="col-sm-12 form-group">
<button class="btn btn-primary afsana-btn" name="submit" value="verzenden" type="submit">Verzenden <i class="ion-arrow-graph-up-right"></i></button>
</div>
</div>
</form>
<?php
if(isset($_POST["submit"])){
// Checking For Blank Fields..
if($_POST["name"]==""||$_POST["email"]==""||$_POST["message"]==""){
echo "Fill All Fields..";
}else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['email'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$subject = (Contact_form);
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$headers .= 'Cc:'. $email2 . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("something#domain.com", $subject, $message, $headers);
echo "Your mail has been sent successfuly ! Thank you for your feedback";
}
}
}
?>
First, you have this: $subject = (Contact_form); which should throw an error, so I assume you have error reporting turned off. When developing, you should have error reporting on so you can see errors in your code... Else you are just working blind. I don't mean by throwing tacky error_reporting(0) in every file either, I mean to set your error reporting level to E_ALL in your php.ini.
You also have: $headers .= 'Cc:'. $email2 . "\r\n";
However, $email2 is not defined anywhere, so you would get an error here too.. which is why it's important to test with error reporting on.
See if this works:
<?php
$error = '';
if(isset($_POST['submit']))
{
if ( !empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message']) )
{
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if ( $email = filter_var($email, FILTER_VALIDATE_EMAIL) )
{
$subject = '(Contact_form)';
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$message = wordwrap($message, 70);
if ( $result = mail("something#domain.com", $subject, $message, $headers) ) {
$error = 'Success';
} else {
$error = 'There was an error sending your email!';
}
} else {
$error = 'Invalid Email Address!';
}
} else {
$error = 'Please fill all fields.';
}
}
?>
<p><?= $error ?></p>
<form action="" method="post">
<input type="text" name="name" value="" /><br />
<input type="email" name="email" value="" /><br />
<textarea name="message" rows="5"></textarea><br />
<input type="submit" name="submit" value="submit" />
</form>
Try to put in $subject just a string value like:
$subject = 'Test subject';
change also the following line to this (there is no $email2 defined):
$headers .= 'Cc:'. $email . "\r\n"; // Carbon copy to Sender
and give it a try. You can also put as first line of your code
<?php error_reporting(E_ALL); ?>
and check for errors when submiting the form.

Contact form - cannot get email to send

I am trying to create a basic form to send an email and here is how it looks:
http://www.unitedserbians.com/contact_us.html
I have everything working and buttoned up, except I cannot get the actual email to be sent once the form has completed processing. My function executes as my field validations work great and I can see the correct values are being grabbed from the form by un-commenting the JAVA script code "alert (dataString);return false;" and even the .ajax executes because I get "Contact Form Sent! We will be in touch soon." message displayed but the actual email never gets sent. I am guessing that something is missing in the process.php file. I cannot trace to see where the issue occurs or if my process.php ever executes. Should the file live in the same directory with JAVA script? or at main directory bin folder? Or is there something I am blindly missing in the process code? Can someone spot what am I missing please? Much appreciated in advance.
HTML:
<div class="content">
<div class="content_resize">
<div class="mainbar">
<div class="article">
<h2><span>Send us E-Mail</span></h2>
<div id="contact_form">
<form action="" form name="contact">
<fieldset>
<ol>
<li>
<label for="name" id="name_label">Your Full Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label2 class="error" for="name" id="name_error">This field is required.</label2>
</li>
<li>
<label for="email" id="email_label">Your Email Address</label>
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
<label2 class="error" for="email" id="email_error">This field is required.</label2>
</li>
<li>
<label for="website id="phone_label">Your Phone Number</label>
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
<label2 class="error" for="phone" id="phone_error">This field is required.</label2>
</li>
<li>
<label for="message">Your Message</label>
<textarea id="message" name="message" rows="8" cols="50"></textarea>
</li>
<li>
<input type="submit" name="imageField" id="submit_btn" src="images/submit.gif" class="send" />
</li>
</ol>
</fieldset>
</form>
</div>
</div>
</div>
JAVA script:
$(function() {
$('.error').hide();
$(".send").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label2#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label2#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label2#phone_error").show();
$("input#phone").focus();
return false;
}
var message = $("textarea#message").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
// alert (dataString);
// return false;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='send_message'></div>");
$('#send_message').html("<h2>Contact Form Sent!</h2>")
.append("<p>We will be in touch soon.</p>");
}
});
return false;
});
});
PHP:
<?php
$email_to = "XXXXX#gmail.com";
$email_subject = "Message sent using contact form.";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // required
$message = $_POST['message'];
$email_message .= "Full Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Phone Number: ".clean_string($phone)."\n";
$email_message .= "Message: ".clean_string($message)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
One possibility is that your host doesn't like the $email_from address. I think most hosts are restrictive about sending using a From address that isn't associated with that host (this is so to not enable spammers). Try using no-reply#yourdomain.com or something like that, or even better an address that really exists, as your From address. The Reply-To can still be the address the user enters (after you check that it is valid).

How to return to the previous page after a submit form with php?

I have a form in html whose "action" attribute calls a contact.php file. The problem is that after I submit the form, the file that is visible is a blank page with the address contact.php and I want to see again the form of the main page.
HTML:
<form id="myForm" action="php-contact/contact.php"
method="post" class="contact_form" autocomplete="off"
role="form">
<div class="form-group">
<label for="input-subject">subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="your subject" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-name">name</label>
<input name="name" type="text" class="form-control" id="name" placeholder="your name" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-email">email address</label>
<input name="email" type="text" class="form-control" id="email" placeholder="your email" maxlength="40"/>
</div>
<div class="form-group" >
<label for="input-message">message</label>
<textarea name="message" cols="10" rows="10" class="form-control" id="comment" ></textarea>
</div>
<button name="myFormSubmitted" type="submit" class="btn btn-primary btn-lg btn-block">send</button>
</form>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "pep.g#gmail.com";
$message = '
name: '.$name.'
email: '.$email.'
message: '.$message.'
';
$headers = 'From: pep.website#website.com';
if (
mail($to, $subject, $message, $headers)
)
echo"<script>alert('message send succesfully')</script>";
else
echo"<script>alert('message not send')</script>";
?>
Use either $_SERVER["HTTP_REFERER"] or use a hidden field on the form with the url of the current page:
<form action="myAction.php">
<input type="hidden" name="destination" value="<?php echo $_SERVER["REQUEST_URI"]; ?>"/>
<!-- other form inputs -->
<input type="submit"/>
</form>
myAction.php
<?php
/* Do work */
if(isset($_REQUEST["destination"])){
header("Location: {$_REQUEST["destination"]}");
}else if(isset($_SERVER["HTTP_REFERER"])){
header("Location: {$_SERVER["HTTP_REFERER"]}");
}else{
/* some fallback, maybe redirect to index.php */
}
And then even then you should have fallbacks in case for some reason the client isn't respecting HTTP redirects, like some redirect javascript, a meta redirect and a link to the destination.
Add a JS redirect after your alert then
echo "<script>
alert('message sent succesfully');
window.history.go(-1);
</script>";
In your contact.php file, just use something like at the end of the PHP code:
header("location:yourfilenamehere.php");
This will redirect back to whatever page you specify.
You could do two things...
1) Have your php logic in the form file and submit to that file. On the top of the file, put something like:
if(isset($_POST['name'])) {
// your sending logic
}
followed by your form.
2) use the header() function to redirect to your form.
header("Location: form.html");
I feel pretty bad about posting this answer as it is just concatenating two other SO answers.
First part
Charlie74's answer on this page
// add the message you want to show to the user
header("Location: yourfilenamehere.php?alertmsg=message+send+succesfully");
exit();
Second part check for the alertmsg name in the query string
See SO post for getParameterByName:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
in the page you are redirecting call the getParameterByName function:
<script>
var msg = getParameterByName('alertmsg');
if (alertmsg.length > 0) {
alert(msg);
}
</script>

Categories

Resources