Ajax form taking a very long time to send emails - javascript

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";
}
?>

Related

How to validate the submit form in JavaScript and solve the problem with the code?

I've get a problem with submit form on the website. When I try to submit the form there is an error:
If I change the method of sending form to action with method POST it works, but I want to solve this problem. I don't know what is wrong. Can you help me?
This is the code of the form
<form id="form-agent" class="ts-form ts-form-email" data-php-path="assets/php/email.php">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Ваше Имя" required="">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Ваш email" required="">
</div>
<div class="form-group">
<textarea class="form-control" id="form-contact-message" rows="3" name="message" placeholder="Здравствуйте, хочу получить информацию об объекте #156461"></textarea>
</div>
<div class="form-group clearfix mb-0">
<button type="submit" class="btn btn-primary float-right" id="form-contact-submit">Отправить сообщение</button>
</div>
</form>
The JS code:
$(".ts-form-email [type='submit']").each(function(){
var text = $(this).text();
$(this).html("").append("<span>"+ text +"</span>").prepend("<div class='status'><i class='fas fa-circle-notch fa-spin spinner'></i></div>");
});
$(".ts-form-email .btn[type='submit']").on("click", function(e){
e.preventDefault();
var $button = $(this);
var $form = $(this).closest("form");
var pathToPhp = $(this).closest("form").attr("data-php-path");
$form.validate ({
submitHandler: function() {
$button.addClass("processing");
$.post( pathToPhp, $form.serialize(), function(response) {
$button.addClass("done").find(".status").append(response).prop("disabled", true);
});
return false;
}
});
});
and PHP file:
<?php
mb_internal_encoding("UTF-8");
$to = 'axwlow#yandex.ru';
$subject = 'Заявка с сайта';
$name = "";
$email = "";
$phone = "";
$message = "";
if( isset($_POST['name']) ){
$name = $_POST['name'];
$body .= "Name: ";
$body .= $name;
$body .= "\n\n";
}
if( isset($_POST['subject']) ){
$subject = $_POST['subject'];
}
if( isset($_POST['email']) ){
$email = $_POST['email'];
$body .= "";
$body .= "Email: ";
$body .= $email;
$body .= "\n\n";
}
if( isset($_POST['phone']) ){
$phone = $_POST['phone'];
$body .= "";
$body .= "Phone: ";
$body .= $phone;
$body .= "\n\n";
}
if( isset($_POST['message']) ){
$message = $_POST['message'];
$body .= "";
$body .= "Message: ";
$body .= $message;
$body .= "\n\n";
}
$headers = 'From: ' .$email . "\r\n";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
mb_send_mail($to, $subject, $body, $headers);
echo '<div class="status-icon valid"><i class="fa fa-check"></i></div>';
}
else{
echo '<div class="status-icon invalid"><i class="fa fa-times"></i></div>';
}

I have 2 forms in a webpage having same code but second form doesnot work

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.

Contact form is sending email but not responding after submission.

I have my contact form set where after submitting it redirects back to my homepage but for some reason it just stays on the same page. I'm trying to receive confirmation after email is sent and then a redirect back to my homepage. I'm using php and javascript...........................................
<div class="col-sm-6 col-sm-offset-3">
<h3>Send me a message</h3>
<form role="form" id="contactForm" action="index2.php" method="POST">
<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>
</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>
</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>
<button type="submit" id="form-submit" class="btn btn-primary btn-lg
pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden">Message Submitted!</div>
</form>
index2.php
<meta http-equiv="refresh" content="0; url=http://myurl.com/" />
</header>
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$EmailTo = "arash281pro#live.com";
$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";
}
?>
js
$("#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: "index2.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
}
function formSuccess(){
$( "#msgSubmit" ).removeClass( "hidden" );
}
var confirmSubmit = true;
$('form').submit(function(e) {
if (confirmSubmit) {
e.stopPropagation();
if (confirm('Are you sure you want to send this form?')) {
confirmSubmit = false;
$('form').submit();
}else{
alert("The form was not submitted.");
}
}
});
You're not actually redirecting back to your homepage.
For that you'll need to add something like this after your submit function:
window.location.replace("index2.php");
Rather than using <meta http-equiv="refresh" content="0; url=http://myurl.com/" /> in index2.php, just add header("Location: http://myurl.com/"); at the end of the script instead of "success" or "invalid" message. Also remove any HTML before the PHP code starts to prevent errors like "Headers already sent, output started on line ..."

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 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