PHP contact form bug - javascript

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.

Related

Display Popup Message in Same Page, for HTML Contact Form by PHP

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.

Stop contact form from replying in new tab. My OCD is fistfighting my ADD over contact form

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();
...
});

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

Ajax php contact form no email

Cannot seem to get this code to work it's says it sending the email but somewhere on the line it's get stuck. have not access to the logs at this moment from the host, so can't check and this should send the emails from my point of view atht this moment
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'The input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Phone = $_POST["userTelephone"];
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name field can not be empty'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please use a valid email address'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a message'));
die($output);
}
$message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$message_Body .= "<strong>Phone: </strong>". $user_Phone ."<br>";
$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$headers = "From: " . strip_tags($user_Email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion() . "\r\n" .
'Content-type: text/html';
$sentMail = #mail($to_Email, $subject, $message_Body, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'An error has occurred, please try again'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hello '.$user_Name .'Thanks for your contact we will return soon.'));
die($output);
}
}
here is the JS
$("#submit_btn").click(function() {
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_telephone = $('input[name=phone]').val();
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
var post_data, output;
var proceed = true;
if(user_name==""){
proceed = false;
}
if(user_email==""){
proceed = false;
}
if(user_message=="") {
proceed = false;
}
//everything looks good! proceed...
if(proceed)
{
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userTelephone':user_telephone, 'userMessage':user_message};
//Ajax post data to server
$.post('contact.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="alert-danger" style="padding:10px; margin-bottom:25px;">'+response.text+'</div>';
}else{
output = '<div class="alert-success" style="padding:10px; margin-bottom:25px;">'+response.text+'</div>';
//reset values in all input fields
$('#form-elements input').val('');
$('#form-elements textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#form-elements input, #form-elements textarea").keyup(function() {
$("#result").slideUp();
});
html
<form id="form-elements" onSubmit="return false">
<div class="row">
<div class="col-md-12 center"><div id="result"> </div> </div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<input type="text" class="form-control" placeholder="Namn" name="name" id="name" required></div>
</div>
<div class="col-sm-4">
<div class="form-group">
<input type="email" class="form-control" placeholder="Email Adress" name="email" id="email" required></div>
</div>
<div class="col-sm-4">
<div class="form-group">
<input type="text" class="form-control" placeholder="Telefon nummer" name="phone" id="phone" required>
</div>
</div>
<div class="col-xs-12">
<textarea id="input" class="form-control" rows="7" required="required" placeholder="Meddelande" name="message" id="message" ></textarea>
</div>
<button type="submit" class="btn btn-default buttons" id="submit_btn">Skicka</button>
</div>
</form>
Dunno but some othere said i should insert
$("#submit_btn").click(function() {
e.preventDefault();
is the problem that I using ?
onSubmit="return false"

php Send mail not working in wordpress

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();
});

Categories

Resources