I have a contact form where the user inputs his name, designation, message etc and is validated using a javascript file called screen.js.
This is my code in the contact form in html view.
<div class="contact_us">
<form id="contactform" action="#" method="post">
<div class="formpart">
<label for="contact_name">Name</label>
<p><input type="text" name="name" id="contact_name" value="" class="requiredfield"/></p>
</div>
<div class="formpart formpart1">
<label for="contact_designation">Designation</label>
<p><input type="text" name="designation" id="contact_designation" value=""/></p>
</div>
<div class="formpart">
<label for="contact_companyname">Company Name</label>
<p><input type="text" name="companyname" id="contact_companyname" value="" class="requiredfield"/></p>
</div>
<div class="formpart formpart1">
<label for="contact_email">Email Address</label>
<p><input type="text" name="email" id="contact_email" value="" class="requiredfield"/></p>
</div>
<div class="formpart">
<label for="contact_phone">Contact No.</label>
<p><input type="text" name="phone" id="contact_phone" value=""/></p>
</div>
<div class="formpart">
<label for="contact_message">Message</label>
<p><textarea name="message" id="contact_message" class="requiredfield"></textarea></p>
</div>
<div class="formpart">
<button type="submit" name="send" class="sendmessage">Send</button>
</div>
<div class="formpart">
<span class="errormessage">Error! Please correct marked fields.</span>
<span class="successmessage">Email send successfully!</span>
<span class="sendingmessage">Sending...</span>
</div>
</form>
</div>
and the javascript file screen.js contains
jQuery(document).ready(function() {
/* Contact Form */
if(jQuery('#contactform').length != 0){
addForm('#contactform');
}
/* Newsletter Subscription */
if(jQuery('#newsletterform').length != 0){
addForm('#newsletterform');
}
});
/* Contact Form */
function addForm(formtype) {
var formid = jQuery(formtype);
var emailsend = false;
formid.find("button[name=send]").click(sendemail);
function validator() {
var emailcheck = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var othercheck = /.{4}/;
var noerror = true;
formid.find(".requiredfield").each(function () {
var fieldname = jQuery(this).attr('name');
var value = jQuery(this).val();
if(fieldname == "email"){
if (!emailcheck.test(value)) {
jQuery(this).addClass("formerror");
noerror = false;
} else {
jQuery(this).removeClass("formerror");
}
}else{
if (!othercheck.test(value)) {
jQuery(this).addClass("formerror");
noerror = false;
} else {
jQuery(this).removeClass("formerror");
}
}
})
if(!noerror){
formid.find(".errormessage").fadeIn();
}
return noerror;
}
function resetform() {
formid.find("input").each(function () {
jQuery(this).val("");
})
formid.find("textarea").val("");
emailsend = false;
}
function sendemail() {
formid.find(".successmessage").hide();
var phpfile = "";
if(formtype=="#contactform"){
phpfile = "../php/contact.php";
}else if(formtype=="#newsletterform"){
phpfile = "php/signup.php";
}else{
phpfile = "";
}
if (validator()) {
if(!emailsend){
emailsend = true;
formid.find(".errormessage").hide();
formid.find(".sendingmessage").show();
jQuery.post(phpfile, formid.serialize(), function() {
formid.find(".sendingmessage").hide();
formid.find(".successmessage").fadeIn();
resetform();
});
}
}
return false
}
}
and my php file contact.php
<?php
$to = "developer#vakilspremedia.com"; /* Enter your email adress here */
$name = trim($_POST['name']);
$designation = trim($_POST['designation']);
$companyname = trim($_POST['companyname']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$message = str_replace(chr(10), "<br>", $_POST['message']);
$body = "<html><head><title>Contact Form Email</title></head><body><br>";
$body .= "Name: <b>" . $name . "</b><br>";
$body .= "Designation: <b>" . $designation . "</b><br>";
$body .= "Company Name: <b>" . $companyname . "</b><br>";
$body .= "Email: <b>" . $email . "</b><br>";
$body .= "Phone: <b>" . $phone . "</b><br><br>";
$body .= "Message:<br><hr><br><b>" . $message . "</b><br>";
$body .= "<br></body></html>";
$subject = 'Contact Form Email from ' . $name;
$header = "From: $to\n" . "MIME-Version: 1.0\n" . "Content-type: text/html; charset=utf-8\n";
mail($to, $subject, $body, $header);
?>
The validation works perfect but when I enter values in all field it shows sending... as the message and doesn't show Email successfully sent at all even after hours and hours of waiting. It seems it does nothing after I click on send button.
Modify ur js for this code make sure phpfile var have url path or put contact.php in same directory
jQuery.post('contact.php', formid.serialize(), function() {
console.log('success');
formid.find(".sendingmessage").hide();
formid.find(".successmessage").fadeIn();
resetform();
});
Related
I have a contact form on my index.html that works with a contact.php file. I need to display a popup message after submitting the form for "message sent" or "something went wrong" without leaving the index.html. Currently, it displays the message in a popup on a blank page.
I truly tried to solve it and I checked a lot of similar questions here, truth is i'm new to php and js (I'm like Jon Snow, I know nothing) and I just couldn't figure out a solution for my case.
I appreciate any help :)
*PHP code:
<?php
if($_POST) {
$visitor_name = "";
$visitor_email = "";
$email_title = "";
$concerned_department = "";
$visitor_message = "";
$email_body = "<div>";
if(isset($_POST['visitor_name'])) {
$visitor_name = filter_var($_POST['visitor_name'], FILTER_SANITIZE_STRING);
$email_body .= "<div>
<label><b>Visitor Name:</b></label> <span>".$visitor_name."</span>
</div>";
}
if(isset($_POST['visitor_email'])) {
$visitor_email = str_replace(array("\r", "\n", "%0a", "%0d"), '', $_POST['visitor_email']);
$visitor_email = filter_var($visitor_email, FILTER_VALIDATE_EMAIL);
$email_body .= "<div>
<label><b>Visitor Email:</b></label> <span>".$visitor_email."</span>
</div>";
}
if(isset($_POST['email_title'])) {
$email_title = filter_var($_POST['email_title'], FILTER_SANITIZE_STRING);
$email_body .= "<div>
<label><b>Reason For Contacting Us:</b></label> <span>".$email_title."</span>
</div>";
}
if(isset($_POST['concerned_department'])) {
$concerned_department = filter_var($_POST['concerned_department'], FILTER_SANITIZE_STRING);
$email_body .= "<div>
<label><b>Concerned Department:</b></label> <span>".$concerned_department."</span>
</div>";
}
if(isset($_POST['visitor_message'])) {
$visitor_message = htmlspecialchars($_POST['visitor_message']);
$email_body .= "<div>
<label><b>Visitor Message:</b></label>
<div>".$visitor_message."</div>
</div>";
}
if($concerned_department == "billing") {
$recipient = "test#mail.com";
}
else if($concerned_department == "marketing") {
$recipient = "test#mail.com";
}
else if($concerned_department == "technical support") {
$recipient = "test#mail.com";
}
else {
$recipient = "test#mail.com";
}
$email_body .= "</div>";
$headers = 'MIME-Version: 1.0' . "\r\n"
.'Content-type: text/html; charset=utf-8' . "\r\n"
.'From: ' . $visitor_email . "\r\n";
if(mail($recipient, $email_title, $email_body, $headers)) {
echo '<script type="text/javascript"> window.onload = function(){
alert("Thank you for contacting us. You will get a reply as soon as possible.");
}</script>';
} else {
echo '<script type="text/javascript"> window.onload = function(){
alert("We are sorry but the email did not go through.");
}</script>';
}
} else {
echo '<script>alert("Something went wrong.")</script>';
}
?>
*HTML code:
<div class="form">
<form action="/php/contact.php" method="post">
<div class="elem-group">
<input type="text" id="name" name="visitor_name" placeholder="Your Name" pattern=[A-Z\sa-z]{3,20} required>
</div>
<div class="elem-group">
<input type="email" id="email" name="visitor_email" placeholder="Your E-mail" required>
</div>
<div class="elem-group">
<input type="text" id="title" name="email_title" required placeholder="Reason For Contacting Us" pattern=[A-Za-z0-9\s]{8,60}>
</div>
<div class="elem-group">
<textarea id="message" name="visitor_message" placeholder="Your Message" required></textarea>
</div>
<button type="submit" class="button white">Send Message</button>
</form>
</div>
Thank you!!
In my opinion, the best way is to use AJAX. My proposition is to create a JS sript that is collecting data and executing php code.
Small change in html:
<div class="form">
<div class="elem-group">
<input type="text" id="name" name="visitor_name" placeholder="Your Name" pattern=[A-Z\sa-z]{3,20} required>
</div>
<div class="elem-group">
<input type="email" id="email" name="visitor_email" placeholder="Your E-mail" required>
</div>
<div class="elem-group">
<input type="text" id="title" name="email_title" required placeholder="Reason For Contacting Us" pattern=[A-Za-z0-9\s]{8,60}>
</div>
<div class="elem-group">
<textarea id="message" name="visitor_message" placeholder="Your Message" required></textarea>
</div>
<button id="contact_submit" type="submit" class="button white">Send Message</button>
</div>
In fact you already has IDs of inputs, creating user side code should be very easy in jQuery:
$("#contact_submit").click(function(){
//Collecting data
let name = $("#name").val();
let email = $("#email").val();
let title = $("#title").val();
let message = $("#message").val();
//AJAX sending data to php code
$.post("/php/contact.php",
{
visitor_name: name,
visitor_email: email,
email_title: title,
visitor_message: message,
},
function(response){
//Response from PHP in alert
//for example: if You use echo "Something went wrong" the message in alert will be the same.
alert(response);
}
);
});
The only thing i would change in PHP is response:
<?php
if($_POST) {
$visitor_name = "";
$visitor_email = "";
$email_title = "";
$concerned_department = "";
$visitor_message = "";
$email_body = "<div>";
if(isset($_POST['visitor_name'])) {
$visitor_name = filter_var($_POST['visitor_name'], FILTER_SANITIZE_STRING);
$email_body .= "<div>
<label><b>Visitor Name:</b></label> <span>".$visitor_name."</span>
</div>";
}
if(isset($_POST['visitor_email'])) {
$visitor_email = str_replace(array("\r", "\n", "%0a", "%0d"), '', $_POST['visitor_email']);
$visitor_email = filter_var($visitor_email, FILTER_VALIDATE_EMAIL);
$email_body .= "<div>
<label><b>Visitor Email:</b></label> <span>".$visitor_email."</span>
</div>";
}
if(isset($_POST['email_title'])) {
$email_title = filter_var($_POST['email_title'], FILTER_SANITIZE_STRING);
$email_body .= "<div>
<label><b>Reason For Contacting Us:</b></label> <span>".$email_title."</span>
</div>";
}
if(isset($_POST['concerned_department'])) {
$concerned_department = filter_var($_POST['concerned_department'], FILTER_SANITIZE_STRING);
$email_body .= "<div>
<label><b>Concerned Department:</b></label> <span>".$concerned_department."</span>
</div>";
}
if(isset($_POST['visitor_message'])) {
$visitor_message = htmlspecialchars($_POST['visitor_message']);
$email_body .= "<div>
<label><b>Visitor Message:</b></label>
<div>".$visitor_message."</div>
</div>";
}
if($concerned_department == "billing") {
$recipient = "test#mail.com";
}
else if($concerned_department == "marketing") {
$recipient = "test#mail.com";
}
else if($concerned_department == "technical support") {
$recipient = "test#mail.com";
}
else {
$recipient = "test#mail.com";
}
$email_body .= "</div>";
$headers = 'MIME-Version: 1.0' . "\r\n"
.'Content-type: text/html; charset=utf-8' . "\r\n"
.'From: ' . $visitor_email . "\r\n";
if(mail($recipient, $email_title, $email_body, $headers)) {
echo 'Thank you for contacting us. You will get a reply as soon as possible.';
} else {
echo 'We are sorry but the email did not go through.';
}
} else {
echo 'Something went wrong.';
}
?>
And it should work, Only thing i could not find was "concerned_department" but i hope you will be albe to add it by yourself. In case you would have problem with it, let me know.
I would give an suggestion to use an alert box as an popup. The code for the same is :
Example:
Add this to your file where you are checking the logic :
if (move_uploaded_file($file, $destination)) {
$sql = "INSERT INTO files (pdf_file) VALUES ('$filename')";
if (mysqli_query($conn, $sql)) {
header("location:form5.php?upload=success");
}
} else {
header("location:form5.php?upload=notsuccess");
}
}
And now add this to your main file :
<?php
if (isset($_GET['upload'])) {
if ($_GET['upload'] == 'success') {
echo '<script>alert("Data added Successfully")</script>';
}
if ($_GET['upload'] == 'notsuccess') {
echo '<script>alert("Data Not added")</script>';
}
}
?>
This will give you an Alert box if the event is successful or unsuccessful stating the same.
this is my html, my php, and ajax for a contact form. It works great except it post the relpys in a new browser tab. I have spent hours trying to correct it. Please help.
html-
<!-- form fields -->
<form action="assets/php/contact.php" method="post" name="contactform" id="contactform" class=" animated out" data-animation="fadeInUp" data-delay="0">
<fieldset>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="text" name="name" id="name" placeholder="Name">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="email" name="email" id="email" placeholder="Email">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="text" name="subject" id="subject" placeholder="Subject">
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" name="message" id="message" placeholder="Message..."></textarea>
</div>
</div>
</div>
</fieldset>
<!-- submit button -->
<div class="form-group">
<input type="submit" name="submit" value="Send message" id="submit" class="btn btn-sm btn-primary">
</div>
<div id="alert"></div>
</form>
PHP-
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if(trim($name) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> You must enter your name.</p></div>';
exit();
} else if(trim($email) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> Please enter a valid email address.</p></div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> You have entered an invalid e-mail address, try again.</p></div>';
exit();
}
if(trim($message) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> Please enter your message.</p></div>';
exit();
}
if(get_magic_quotes_gpc()) {
$message = stripslashes($message);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
$address = "your#email.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name ." . PHP_EOL . PHP_EOL;
$e_content = "\"$message\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<div class='notification success clearfix'><p>Thank you <strong>$name</strong>, your message has been submitted to us.</p></div>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
JS-
/* ==============================================
Contact Form
=============================================== */
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#alert").slideUp(750,function() {
$('#alert').hide();
$('#submit')
.after('<img src="assets/images/ajax-loader.GIF" class="contactloader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
},
function(data){
document.getElementById('alert').innerHTML = data;
$('#alert').slideDown('slow');
$('#contactform img.contactloader').fadeOut('slow',function(){$(this).remove();});
$('#submit').removeAttr('disabled');
if(data.match('success') !== null) {
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
}
);
});
return false;
});
I want error or success messages to show on the contact.html page and not open a new browser tab.
Thank you advance for help restore my sanity.
Cheers
You just need to prevent the default form submit from firing, which will post the content to the URL in your form action.
$('#contactform').submit(function(event){
event.preventDefault();
...
});
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
I have a webpage which contains 2 contact form one at the banner and another at the bottom of the webpage at contact details. I have being using php for this. However the mail gets submitted of the first form but not of the second form. But in case if I remove the first form from the website, the second form works absolutely fine. I would like to know the reason for it if any body can help. You can refer to website http://www.infinitesignalsolution.com
<form role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name" required data-error="NEW ERROR MESSAGE">
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="sub" class="h4">Sub</label>
<input type="sub" id="sub" class="form-control" placeholder="Enter Subject" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="message" class="h4">Message</label>
<textarea id="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="btn btn-success btn-lg pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
JavaScript
$("#contactForm").validator().on("submit", function (event)
{
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Did you fill in the form properly?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm()
{
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var sub = $("#sub").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&sub=" + sub + "&message=" + message,
success : function(text)
{
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess()
{
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError()
{
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg)
{
if(valid){
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
PHP
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
if (empty($_POST["phone"])) {
$errorMSG = "Phone No is required ";
} else {
$phone = $_POST["phone"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailFrom = "info#infinitesignalsolution.com";
$EmailTo = "umar.neha06#gmail.com";
$Subject = "Enquiry received from website";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Phone: ";
$Body .= $phone;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$EmailFrom);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
Do both forms have the same ID? If so, give them unique ID's, but give them a common css class.
Then refer to $(".contactForm") instead. As for the fields, you can give them a class but target the correct ones using $(this).find('.field-class') inside the submit function.
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.