Fix contact form - Messages sent successfully - javascript

I have a landing page in HTML that involves sending data via a contact form. But if you try to use the contact form, when you click the 'Submit' button, you open a new PHP page with 'Success'. How can I do that when I click 'Submit' does not open a page, but a text appears under the 'Send' button with the text 'Messages sent successfully'?
I cannot fix this problem. What should I change in my HTML and my PHP?
Here is an example image of what I would like to do:
HTML CODE:
<!-- Form -->
<form class="contact-form" role="form" method="post" action="php/form-process.php">
<i class="mdi-action-account-box"></i>
<input type="text" class="form-control" name="name" placeholder="Nome" required="required">
<i class="mdi-content-mail"></i>
<input type="email" class="form-control" name="email" placeholder="Email" required="required">
<textarea class="form-control" name="message" placeholder="Messaggio" rows="4" required="required"></textarea>
<input type="checkbox" name="trattdati" required /> Accetto il trattamento dei miei dati ai sensi del D.Lgs. 196/03<br />
<input type="checkbox" name="provasoftware" /> Desidero provare il software
<br /><br />
<button type="submit" id="submit" class="btn btn-lg btn-primary"
style="float:left">Invia</button>
<div id="success" class="success" style=" color: #009688;
font-size: 20px;
margin-top: -16px;
float: left;
margin-left: 25px;">
</div>
</form>
<script>
$(document).ready(function() {
// This command is used to initialize some elements and make them work properly
$.material.init();
var options = {
target: '#success', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
// pre-submit callback
function showRequest(formData, jqForm, options) {
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
$('.contact-form')[0].reset();
$('.contact-form').trigger("reset");
}
// bind form using 'ajaxForm'
$('.contact-form').ajaxForm(options);
});
</script>
PHP FILE:
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// MSG SUBJECT
//if (empty($_POST["msg_subject"])) {
// $errorMSG .= "Subject is required ";
//} else {
// $msg_subject = $_POST["msg_subject"];
//}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "bagiacchimarco7#gmail.com";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
//$Body .= "Subject: ";
//$Body .= $msg_subject;
//$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>

Assuming you are using the Javascript correctly as per the documentation for whatever plugin you are using, you should be able to simply do:
function showResponse(responseText, statusText, xhr, $form) {
$('#success').html(responseText);
$('.contact-form')[0].reset();
$('.contact-form').trigger("reset");
}
Again, I'm making assumptions, but responseText should contain the data from your PHP page. #success looks like the div where you want your form feedback to go and the html jQuery function will allow you to put the responseText into the #success div.
Granted the other answers all show ways of doing this without your plugin, but it appears you are using a jQuery plugin.
EDIT
After reading the documentation on your plugin I think you may just need to add:
$('.contact-form').submit(function() {
// submit the form
$(this).ajaxSubmit();
// return false to prevent normal browser submit and page navigation
return false;
});
You need to thoroughly read the documentation about all of the plugins you are using.
EDIT2
Try changing Raj's code to
$('#submit').click(function(e){
e.preventDefault() //Prevent the default action of the form.
$.post( //Send a POST request to the PHP file via AJAX
"php/form-process.php", //Path to the PHP file where you want to send the POST
$(.contact-form).serializeArray().reduce(function(obj, item) {
obj[item.name] = item.value;
return obj;
}, {}), // This takes all the form fields and returns key-value pairs of form data
function (data) { //data = response from the PHP file. In your case "Sucess"
if(data==="success"){
//do something with data. Have assumed you want to append it to a div called "response". You will need to add <div id="success"> </div> below your form
$('#success').html(data);
} else {
$('#success').html("Sorry Try Again");
}
});
)}

You need to send a POST request via AJAX to your PHP file and handle the response on the DOM.
jQuery/AJAX code
$('#submit').click(function(e)
e.preventDefault() //Prevent the default action of the form.
$.post( //Send a POST request to the PHP file via AJAX
"path/to/file.php", //Path to the PHP file where you want to send the POST
$(.contact-form).serializeArray().reduce(function(obj, item) {
obj[item.name] = item.value;
return obj;
}, {}) // This takes all the form fields and returns key-value pairs of form data
, function (data) { //data = response from the PHP file. In your case "Sucess"
if(data==="success"){
//do something with data. Have assumed you want to append it to a div called "response". You will need to add <div id="response"> </div> below your form
$('#response').html(data);
} else {
$('#response').html("Sorry Try Again");
}
//Alternatively you can just append data to response and not have this IF
});
)
Also do check out validate.js. It handles validation of the form on the front end itself and also has a really nice method to submit forms and manage responses.

You could use if submit button was clicked and all filled out then redirect to success_page.php Just add name="submit" and it should work HTML:
UPDATE 2 : Working Example --->> sample website (DOnt mind the errors its just a quick example you can play around with it yourself. I added the php into the html file and it work. Hopfully this will help you.
UPDATE: If you include your php page in the div you want it should print out the message.
<form class="contact-form" role="form" method="post" action="">
<i class="mdi-action-account-box"></i>
<input type="text" class="form-control" name="name" placeholder="Nome" required="required">
<i class="mdi-content-mail"></i>
<input type="email" class="form-control" name="email" placeholder="Email" required="required">
<textarea class="form-control" name="message" placeholder="Messaggio" rows="4" required="required"></textarea>
<input type="checkbox" name="trattdati" required /> Accetto il trattamento dei miei dati ai sensi del D.Lgs. 196/03<br />
<input type="checkbox" name="provasoftware" /> Desidero provare il software
<br /><br />
<button type="submit" id="submit" class="btn btn-lg btn-primary" style="float:left">Invia</button>
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// MSG SUBJECT
//if (empty($_POST["msg_subject"])) {
// $errorMSG .= "Subject is required ";
//} else {
// $msg_subject = $_POST["msg_subject"];
//}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "bagiacchimarco7#gmail.com";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
//$Body .= "Subject: ";
//$Body .= $msg_subject;
//$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success message sent!";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
<div id="success" class="success" style=" color: #009688;
font-size: 20px;
margin-top: -16px;
float: left;
margin-left: 25px;">
</div>
</form>

Related

Data from new HTML form input field not being passed to email using PHP and JavaScript

This is my first post on the site. I added a new input field to a previously working HTML contact form in order to collect the user’s street address. Although all other input fields continue to pass data to the email generated after the form is submitted, data is not being passed to the email with the street address. I have copied below the associated HTML, PHP, and JavaScript files, as well as an example of what data is now sent to the email.
I truly appreciate any help with what I am doing wrong. I have spent over 8 hours trying to solve this problem, but so far have been unsuccessful. Thank you!
Here is an example of the data now being placed into the email generated. Notice that the only data NOT being passed is the text that was input into the street address field of the contact form (blank).
Name: Tim Spyridon
Address:
Phone Number: 513-662-1464
Message:
Made major changes to PHP script. This may work!
Here is the HTML code used for the contact form:
<!-- Form Starts -->
<div id="contact_form">
<div class="form-group">
<label>Name <span class="required">*</span></label>
<input placeholder="Your Name" type="text" name="name" class="form-control input-field" required>
<label>Street Address and City <span class="required">*</span></label>
<input placeholder="Your Street Address and City" type="text" name="address" class="form-control input-field" required>
<label>Email Address <span class="required">*</span></label>
<input placeholder="Your Email Address" type="email" name="email" class="form-control input-field" required>
<label>Phone Number including Area Code <span class="required">*</span></label>
<input placeholder="Your 10-Digit Phone Number" type="tel" name="phone" class="form-control input-field" required>
<label>Message <span class="required">*</span></label>
<textarea placeholder="Type your message here ..." name="message" id="message" class="textarea-field form-control" rows="3" required></textarea>
</div>
<div class="text-right">
* Required Field
</div>
<button type="submit" id="submit_btn" value="Submit" class="btn center-block">Send message</button>
</div>
Here is my JavaScript code from a file called contact.js:
"use strict";
jQuery(document).ready(function($) {
$("#submit_btn").on("click", function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required], #contact_form textarea[required]").each(function() {
$(this).css('background-color', '');
if (!$.trim($(this).val())) { //if this field is empty
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($(this).attr("type") === "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
});
if (proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var post_data = {
'user_name': $('input[name=name]').val(),
'user_address': $('input[name=address]').val(),
'user_email': $('input[name=email]').val(),
'phone': $('input[name=phone]').val(),
'msg': $('textarea[name=message]').val()
};
//Ajax post data to server
$.post('php/sendmail.php', post_data, function(response) {
if (response.type === 'error') { //load json data from server and output message
var output = '<br><br><div class="error">' + response.text + '</div>';
} else {
var output = '<br><br><div class="success">' + response.text + '</div>';
//reset values in all input fields
$("#contact_form input, #contact_form textarea").val('');
}
$('html, body').animate({scrollTop: $("#contact_form").offset().top-50}, 2000);
$("#contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('background-color', '');
$("#result").slideUp();
});
});
Here is my PHP script from a file called sendmail.php:
<?php
if($_POST)
{
$to_email1 = "kim#twotailsup.com"; //Recipient email, Replace with own email here
$to_email2 = "tim#twotailsup.com"; //Recipient email, Replace with own email here
$email_subject = "Message from Website Contact Form";
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_address = filter_var($_POST['user_address'], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$message_body = "Name: " . $user_name . "\n"
. "Address: " . $user_address . "\n"
. "Email: " . $user_email . "\n"
. "Phone Number: " . $phone . "\n"
. "Message: " . "\n" . $message;
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email1, $email_subject, $message_body, $headers);
$send_mail = mail($to_email2, $email_subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => '<p>Could not send mail! Please check your PHP mail configuration.</p>'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => '<div class="alert alert-success" role="alert">
Hi '.$user_name .', Thank you for your message! We will get back to you soon.</div>'));
die($output);
}
}
?>
In support of the comment made last night (above ) here is the test version of the above script which appears to work perfectly well in terms of the newly added message field. There are comments at places where things were changed - some semantic, others functional.
<?php
if( $_POST ){
# Simple Boolean to switch between live & test mode
# whilst testing that this script does or does not
# function correctly.
$b_live=false;
$to_email1 = "kim#twotailsup.com"; //Recipient email, Replace with own email here
$to_email2 = "tim#twotailsup.com"; //Recipient email, Replace with own email here
$email_subject = "Message from Website Contact Form";
//check if its an ajax request, exit if not
if( !isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) AND strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) != 'xmlhttprequest' ) {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_address = filter_var($_POST['user_address'], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$message_body = "Name: " . $user_name . "\n"
. "Address: " . $user_address . "\n"
. "Email: " . $user_email . "\n"
. "Phone Number: " . $phone . "\n"
. "Message: " . "\n" . $message;
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
# If the script is live, attempt to send the emails
if( $b_live ){
$send_mail = mail($to_email1, $email_subject, $message_body, $headers);
$send_mail = mail($to_email2, $email_subject, $message_body, $headers);
}else{
# emulate either a success or failure randomly
# to aid testing of ajax callback
$send_mail=mt_rand(0,1);
# you can verify the message is being populated
$_POST['MESSAGE']=$message;
$_POST['TIME']=date( DATE_ATOM );
file_put_contents( __DIR__ . '/ajax.log', json_encode( $_POST ) . PHP_EOL, FILE_APPEND );
}
if(!$send_mail){
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => '<p>Could not send mail! Please check your PHP mail configuration.</p>'));
die( $output );
}else{
$output = json_encode(array('type'=>'message', 'text' => '<div class="alert alert-success" role="alert">
Hi '.$user_name .', Thank you for your message! We will get back to you soon.</div>'));
die( $output );
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<title>Contact</title>
</head>
<body>
<!--
The `label` attribute **must** be associated with whichever form element
it is supposed to reference. This can be done either by including the
`for` attribute in the label with the input element's ID OR the form element
must be within the label itself - as shown below.
-->
<div id="contact_form">
<div class="form-group">
<label>
Name <span class="required">*</span>
<input placeholder="Your Name" type="text" name="name" class="form-control input-field" required />
</label>
<label>
Street Address and City <span class="required">*</span>
<input placeholder="Your Street Address and City" type="text" name="address" class="form-control input-field" required />
</label>
<label>
Email Address <span class="required">*</span>
<input placeholder="Your Email Address" type="email" name="email" class="form-control input-field" required />
</label>
<label>
Phone Number including Area Code <span class="required">*</span>
<input placeholder="Your 10-Digit Phone Number" type="tel" name="phone" class="form-control input-field" required />
</label>
<label>
Message <span class="required">*</span>
<textarea placeholder="Type your message here ..." name="message" id="message" class="textarea-field form-control" rows="3" required /></textarea>
</label>
</div>
<div class="text-right">
* Required Field
</div>
<button type="submit" id="submit_btn" value="Submit" class="btn center-block">Send message</button>
</div>
<!--
Added this DIV to allow output to be rendered
-->
<div id='contact_results'></div>
<script>
"use strict";
jQuery(document).ready(function($) {
$("#submit_btn").on("click", function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required], #contact_form textarea[required]").each(function() {
$(this).css('background-color', '');
if (!$.trim($(this).val())) { //if this field is empty
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($(this).attr("type") === "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
});
if (proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var post_data = {
'user_name': $('input[name=name]').val(),
'user_address': $('input[name=address]').val(),
'user_email': $('input[name=email]').val(),
'phone': $('input[name=phone]').val(),
'msg': $('textarea[name=message]').val()
};
//Ajax post data to server
/*
*****************************************************
This is the ONLY change made in the Javascript
*****************************************************
*/
const _URL=location.href; // 'php/sendmail.php'
$.post( _URL, post_data, function(response) {
if (response.type === 'error') { //load json data from server and output message
var output = '<br><br><div class="error">' + response.text + '</div>';
} else {
var output = '<br><br><div class="success">' + response.text + '</div>';
$("#contact_form input, #contact_form textarea").val('');
}
$('html, body').animate({scrollTop: $("#contact_form").offset().top-50}, 2000);
$("#contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('background-color', '');
$("#result").slideUp();
});
});
</script>
</body>
</html>
With this I could not replicate the issues stated in the question: The $message variable is populated and can be inspected in the console or the ajax.log file that is generated in test mode.

How do I fix the POST 405 error for an email form (PHP) hosted on http-server?

I am new to PHP and jQuery. I wanted to test the functionality for the email contact form in PHP that I call from my jQuery file. I have been filling in the details on the form correctly, however, whenever I press the "Submit" button, I get 405 error.
To be more precise, I get "POST http://192.168.87.1:8080/js/inc/contactformhandler.php 405 (Method Not Allowed)" from jquery-3.4.1.min.js:2. I am running my website on http-server !.
My HTML form:
<div class="row contact-form">
<div class="col-twelve">
<!-- form -->
<form name="contactForm" id="contactForm" method="POST">
<fieldset>
<div class="form-field">
<input name="contactName" type="text" id="contactName" placeholder="Name" value="" minlength="2" required="">
</div>
<div class="form-field">
<input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="">
</div>
<div class="form-field">
<input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="">
</div>
<div class="form-field">
<textarea name="contactMessage" id="contactMessage" placeholder="message" rows="10" cols="50" required=""></textarea>
</div>
<div class="form-field">
<button class="submitform">Submit</button>
<div id="submit-loader">
<div class="text-loader">Sending...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
</fieldset>
</form> <!-- Form End -->
<!-- contact-warning -->
<div id="message-warning">
</div>
<!-- contact-success -->
<div id="message-success">
<i class="fa fa-check"></i>Your message was sent, thank you!<br>
</div>
</div> <!-- /col-twelve -->
</div> <!-- /contact-form -->
JS code where I try to load the contactformhandler.php:
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('#submit-loader');
$.ajax({
type: "POST",
url: "js/inc/contactformhandler.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.fadeIn();
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
sLoader.fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
},
error: function() {
sLoader.fadeOut();
$('#message-warning').html("Something went wrong with loader. Please try again.");
$('#message-warning').fadeIn();
}
});
}
});
contactformhandler.php:
<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
// Replace this with your own email address
$siteOwnersEmail = 'krysbaran#gmail.com';
if(isset($_POST["submit"])) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'MyWebsiteEmail';
$mail->Password = 'MyPassword';
$mail->SMTPSecure = 'ssl'; //<---- THIS is the problem
$mail->Port = 465;
$mail->setFrom('MyWebsiteEmail', 'My Website');
$mail->addAddress($siteOwnersEmail, 'Krzysztof Baran');
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = 'test text';
try {
$mail->send();
echo 'OK';
}
catch (phpmailerException $e) {
echo $e->errorMessage();
} catch (Exception $e) {
$e->getMessage();
}
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
I expect the website to display box saying Your message was sent, thank you! but I am getting Something went wrong with loader. Please try again.
You should use form in .php file not in .html file

PHP Contact form submits without needing all fields filled in

I have a PHP contact form which works even if the fields are not filled in. This hasn't been a problem until recently when I've started to get handfuls of blank emails every day.
How do enforce all fields to be filled out in the form before the submit button can be used?
Here is my PHP code below:
<?php
header("Access-Control-Allow-Origin: *");
$EmailFrom = "myemail";
$EmailTo = "myemail";
$Subject = "subject goes here";
$Email = Trim(stripslashes($_POST['email']));
$Message = Trim(stripslashes($_POST['message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom" . "\r\n" );
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
And here is my HTML markup:
<!-- CONTACT FORM -->
<div class="span9 contact_form">
<div id="note"></div>
<div id="fields">
<div id="post-ajax" style="display: none;"></div>
<form id="contact-form-face" class="clearfix" action="/php/contactengine.php">
<input type="text" name="email" value="Email" onFocus="if (this.value == 'Email') this.value = '';" onBlur="if (this.value == '') this.value = 'Email';" />
<textarea name="message" onFocus="if (this.value == 'Message') this.value = '';" onBlur="if (this.value == '') this.value = 'Message';">Message</textarea>
<input class="contact_btn" name="submit" type="submit" value="Send Message" />
</form>
</div>
</div>
<!-- //CONTACT FORM -->
I can't find your fields. But in general, HTML5 provides a very convenient way to make a form field required. To do so, you can add a required attribute in your form elements, such as:
<input type="text" name="txt_name" required />
Modern browsers will validate the fields during form submit. To support older browsers, you can use JS validation libraries for client-side validation and use PHP condition check, e.g. if(!empty($_POST['txt_name'])) for server-side validation.
Moreover, it is suggested not to use meta refresh tag for redirection; use header('Location: error.htm'); exit; for example, instead.
<!-- CONTACT FORM -->
<div class="span9 contact_form">
<div id="note"></div>
<div id="fields">
<div id="post-ajax" style="display: none;"></div>
<form id="contact-form-face" class="clearfix" action="/php/contactengine.php">
<input type="text" name="email" value="Email" onFocus="if (this.value == 'Email') this.value = '';" onBlur="if (this.value == '') this.value = 'Email';" required />
<textarea name="message" onFocus="if (this.value == 'Message') this.value = '';" onBlur="if (this.value == '') this.value = 'Message';" required>Message</textarea>
<input class="contact_btn" name="submit" type="submit" value="Send Message" />
</form>
</div>
</div>
<!-- //CONTACT FORM -->
Apart from adding the required attribute as indicated in the other answer(which can be by passed very easy through inspect element) you also need validation in the server side as well before processing.
You can create an array of the required fields then check, if those fields are set and not empty.
<?php
$errors = "";
$requiredFields = array("email","message"); // enter the name in the inputs, ie name="someInput"
foreach($requiredFields as $fieldname){
if(!isset($_POST[$fieldname]) && empty($_POST[$fieldname])){
$errors++;
echo "Enter all fields";
//OR redirect to error page
}
}
if($errors <=0){
// Proccess the form
$EmailFrom = "myemail";
$EmailTo = "myemail";
$Subject = "subject goes here";
$Email = Trim(stripslashes($_POST['email']));
$Message = Trim(stripslashes($_POST['message']));
// prepare email body text
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom" . "\r\n" );
// redirect to success page
if ($success){
header("location:contactthanks.php");
exit();
}
else{
header("location:error.htm")
exit();
}
}
?>

PHP contact form bug

I have a contact form using html and i also have a sendEmail.php file.
Everything works on the front end and notified that the email has been sent but it never seems to come to my inbox.
I can't identify why this is happening?
Help is much appreciated.
Thanks in advance.
Here is HTML
<div class="form-field">
<input name="contactName" type="text" id="contactName" placeholder="Name" value="" minlength="2" required="">
</div>
<div class="row">
<div class="col-six tab-full">
<div class="form-field">
<input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="">
</div>
</div>
<div class="col-six tab-full">
<div class="form-field">
<input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="">
</div>
</div>
</div>
<div class="form-field">
<textarea name="contactMessage" id="contactMessage" placeholder="message" rows="10" cols="50" required=""></textarea>
</div>
<div class="form-field">
<button class="submitform">Submit</button>
<div id="submit-loader">
<div class="text-loader">Sending...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
</form>
<!-- contact-warning -->
<div id="message-warning"></div>
<!-- contact-success -->
<div id="message-success">
<i class="fa fa-check"></i>Your message was sent, thank you!<br>
</div>
Here is the sendEmail.php
$siteOwnersEmail = 'info#jalina-digital.co.uk';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
And here is some JS.
var ssContactForm = function() {
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('#submit-loader');
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.fadeIn();
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
sLoader.fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
},
error: function() {
sLoader.fadeOut();
$('#message-warning').html("Something went wrong. Please try again.");
$('#message-warning').fadeIn();
}
});
}
});
};
The code you have written has some errors.
1) In your HTML form it show <button class="submitform">Submit</button> you must just a name to that input example <input type="submit" name="send" class="submitform">Submit</input>
2) In your PHP sendEmail file if($_POST) must become if(isset($_POST['send']))
Accordingly making these corrections will solve. Also Note Sending mail in PHP will not instant receive msg this may take some time.

Ajax form taking a very long time to send emails

I have an Ajax contact form on my site which actually currently works but the email that it compiles from the form is taking around 50 minutes to arrive in my inbox, here is the code, does anyone know what could be causing this excessive time gap?
Jquery
$("#contactForm").submit(function(event){
// cancels the form submission
event.preventDefault();
submitForm();
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
}
function formSuccess(){
$( "#msgSubmit" ).removeClass( "hidden" );
}
HTML
<div id="form-container">
<form role="form" id="contactForm">
<input id="name" class="input" type="text" placeholder="Your name" name="name">
<input id="email" class="input" type="text" placeholder="Contact email address" name="email">
<textarea id="message" class="input message" placeholder="What would you like to discuss?" name="message"></textarea>
<input id="form-submit" class="submit" type="submit" value="Send Message" name="submit">
</form>
</div>
PHP
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$EmailTo = "contact#etcetcetc.co.uk";
$Subject = "New Message Received";
// prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success){
echo "success";
}else{
echo "invalid";
}
?>

Categories

Resources