email file attachment php, Ajax, Jquery - javascript

i have problem with email file attachment php, Ajax, Jquery on the following codes, also i need the file attachment field mandatory. the uploaded file in the form doesn't pass to the email!
i need to place code into the Ajax to receive file(s) from the form and check the empty field, then it everything goes fine pass the fields include file(s) to the form. and from the form to the Email.
HTML Form:
<form role="form">
<div class="form-group">
<label for="inputName" class="form-label "></label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
</div>
<div class="form-group">
<label for="inputEmail" class="form-label "></label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage" class="form-label "></label>
<input type="text" class="form-control" id="inputMessage" placeholder="Phone Example:+1234567890"></textarea>
</div>
</form>
<button type="button" class="btn sign-btn-primary submitBtn" onclick="submitContactForm()">Request</button>
<p class="statusMsg"></p>
my php file :
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
/*
* Send email to admin
*/
$to = 'info#test.org';
$subject= 'CCI2017 Download Log';
$htmlContent = '
<h4>The CCI 2017 has been downloaded by person, details are given below.</h4>
<table cellspacing="0" style="width: 300px; height: 200px;">
<tr>
<th>Name:</th><td>'.$name.'</td>
</tr>
<tr style="background-color: #e0e0e0;">
<th>Email:</th><td>'.$email.'</td>
</tr>
<tr>
<th>Phone:</th><td>'.$message.'</td>
</tr>
</table>';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: ME' . "\r\n";
// Send email
if(mail($to,$subject,$htmlContent,$headers)){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
}
my jquery:
<script type="application/javascript">
function submitContactForm() {
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var regp = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
if (name.trim() == '') {
alert('Please enter your name.');
$('#inputName').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else if (message.trim() != '' && !regp.test(message)) {
alert('Please enter your Phone.');
$('#inputMessage').focus();
return false;
} else {
$.ajax({
type: 'POST',
url: 'submit_form.php',
data: 'contactFrmSubmit=1&name=' + name + '&email=' + email + '&message=' + message,
beforeSend: function () {
$('.submitBtn').attr("disabled", "disabled");
$('.modal-body').css('opacity', '.5');
},
success: function (msg) {
if (msg == 'ok') {
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('.statusMsg').html('Download');
} else {
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>

Solutions:
<form role="form">
<div class="form-group">
<label for="inputName" class="form-label "></label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
</div>
<div class="form-group">
<label for="inputEmail" class="form-label "></label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage" class="form-label "></label>
<input type="text" class="form-control" id="inputMessage" placeholder="Phone Example:+1234567890"></textarea>
</div>
</form>
<button type="button" class="btn sign-btn-primary submitBtn" onclick="submitContactForm()">Request</button>
<p class="statusMsg"></p>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="application/javascript">
function submitContactForm() {
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var regp = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
if (name.trim() == '') {
alert('Please enter your name.');
$('#inputName').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else if (message.trim() != '' && !regp.test(message)) {
alert('Please enter your Phone.');
$('#inputMessage').focus();
return false;
} else {
$.ajax({
type: 'POST',
url: 'submit_form.php',
data: 'contactFrmSubmit=1&name=' + name + '&email=' + email + '&message=' + message,
beforeSend: function () {
$('.submitBtn').attr("disabled", "disabled");
$('.modal-body').css('opacity', '.5');
},
success: function (msg) {
if (msg == 'ok') {
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('.statusMsg').html('Download');
} else {
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
Submit_form.php
<?php
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
$to = 'kiran.mind2014#gmail.com';
// Subject
$subject = 'CCI2017 Download Log';
// Message
$message = '
<h4>The CCI 2017 has been downloaded by person, details are given below.</h4>
<table cellspacing="0" style="width: 300px; height: 200px;">
<tr>
<th>Name:</th><td>'.$name.'</td>
</tr>
<tr style="background-color: #e0e0e0;">
<th>Email:</th><td>'.$email.'</td>
</tr>
<tr>
<th>Phone:</th><td>'.$message.'</td>
</tr>
</table>
';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: Kiran <kiran.mind2014#gmail.com>';
$headers[] = 'From: CCI2017 Download Log <kiran.mind2014#gmail.com>';
// Send email
if(mail($to, $subject, $message, implode("\r\n", $headers))){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
It is working fine!!!.

Related

How to return JSON in HTML using PHP and AJAX without redirecting?

I have searched a lot for a solution to this problem but I have not found one for it. I am trying to include a form for sending e-mails (a contact us form) on my site (using Bootstrap). PHP is being used for the mailer model.
The problem lies in the message that should appear to the user when the message is sent, the message does not appear in the place assigned to it(#status), but rather I am directed to a new page with array data.https://drive.google.com/file/d/1tH8cVCWpx7pDe2OyxkGSKY6rnqV9KxlL/view?usp=sharing
Note that the message appears in all verification cases (when name or email or subject or message fields is empty), only when the email is sent, it directs me to another page!https://drive.google.com/file/d/1lK11R2a18S2arExDegcZyOnITwRlIOYh/view?usp=sharing
Here is my code:
< script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" > < /script> <
script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" > < /script> <
script >
function validateForm() {
document.getElementById('status').innerHTML = "Sending...";
formData = {
'name': $('input[name=name]').val(),
'email': $('input[name=email]').val(),
'subject': $('input[name=subject]').val(),
'message': $('textarea[name=message]').val()
};
$.ajax({
url: "mail.php",
type: "POST",
data: formData,
dataType: "json",
success: function(data, textStatus, jqXHR) {
$('#status').text(data.message1);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], textarea").val("");
},
error: function(jqXHR, textStatus, errorThrown) {
$('#status').text(jqXHR);
}
});
} <
/script>
<div class="col-lg-8">
<form id="contact-form" name="contact-form" action="mail.php" method="POST">
<div class="row ">
<div class="form-group col-md-6">
<input class="form-control" placeholder="Name" id="name" name="name" required="required">
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" placeholder="Email" id="email" name="email" required="required">
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control" placeholder="Subject" id="subject" name="subject" required="required">
</div>
<div class="form-group col-md-12">
<textarea type="text" class="form-control" rows="6" placeholder="Message" id="message" name="message" required="required"></textarea>
</div>
</div>
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-lg btn-primary ml-auto" onclick="validateForm();">Send Message</button>
</div>
<div class="status" id="status"></div>
</form>
</div>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
header('Content-Type: application/json');
$data = array();
if ($name === ''){
$data['message1'] = 'Name cannot be empty.';
$data['code'] = 0;
print json_encode($data);
exit();
}
if ($email === ''){
$data['message1'] = 'Email cannot be empty.';
$data['code'] = 0;
print json_encode($data);
exit();
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$data['message1'] = 'Email format invalid.';
$data['code'] = 0;
print json_encode($data);
exit();
}
}
if ($subject === ''){
$data['message1'] = 'Subject cannot be empty.';
$data['code'] = 0;
print json_encode($data);
exit();
}
if ($message === ''){
$data['message1'] = 'Message cannot be empty.';
$data['code'] = 0;
print json_encode($data);
exit();
}
$content="From: $name \nEmail: $email \nMessage: $message";
$recipient = "******#gmail.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
$data['message1'] = 'Email successfully sent!';
$data['code'] = 1;
print json_encode($data);
exit();
?>
The problem you experience is that upon the form's submission's default behavior is the behavior you usually see when browsers are interacting with the HTTP protocol. Your button is of type submit and it submits the form.
Assuming that you handle all the logic that you want inside validateForm, the thing your code is missing is that your intention is to prevent the default behavior on submit:
$("#contact-form").submit(function(e) {
e.preventDefault();
});

I need help to fix a blank emails from my form

I'm getting everyday in around the same hour 6 blank emails from my contact form, if I fill the form in the website all the info go through and I'm getting the email with the details, I have a validation for my form but still getting the blank emails. What do I need to do?
At the beginning I was getting an error for some lines in my php but it's already fixed but I'm still getting the blank emails.
This is My PHP code:
$fname = $lname = $email = $tel = $address = $project = $message = '';
if (isset($_POST['fname'])) {
$fname = $_POST['fname'];
}
if (isset($_POST['lname'])) {
$lname = $_POST['lname'];
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
if (isset($_POST['tel'])) {
$tel = $_POST['tel'];
}
if (isset($_POST['address'])) {
$address = $_POST['address'];
}
if (isset($_POST['project'])) {
$project = $_POST['project'];
}
if (isset($_POST['message'])) {
$message = $_POST['message'];
}
$to = '...';
$email_subject = "$fname $lname Contact You from ... :";
$email_body = "You have received a new message from your website contact form.<br/>"."Here are the details:<br/><br/> Name: $fname $lname<br/> Email: $email<br/> Phone: $tel<br/> Address: $address<br/> Project: $project<br/> Message:\n$message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: ...' . "\r\n";
$headers .= 'Reply-To: ...' . "\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
if(mail($to,$email_subject,$email_body,$headers)) {
echo "OK";
}
This Is my HTML code:
<form action="" method="post" role="form" class="contactForm" enctype="multipart/form-data">
<div class="row">
<div class="col-lg-6 form-group">
<label for="fname">First Name*</label>
<input type="text" class="form-control" name="fname" id="fname" data-rule="minlen:3" data-msg="*Please Enter at Least 3 Chars" />
<div class="validation"></div>
</div>
<div class="col-lg-6 form-group">
<label for="lname">Last Name*</label>
<input type="text" class="form-control" name="lname" id="lname" data-rule="minlen:3" data-msg="*Please Enter at Least 3 Chars" />
<div class="validation"></div>
</div>
<div class="col-lg-6 form-group">
<label for="tel">Phone Number*</label>
<input type="tel" class="form-control" name="tel" id="tel" data-rule="minlen:10" data-msg="*Please Enter a Valid Phone Number" />
<div class="validation"></div>
</div>
<div class="col-lg-6 form-group">
<label for="email">Email Address*</label>
<input type="email" class="form-control" name="email" id="email" data-rule="email" data-msg="*Please Enter a Valid Email Address" />
<div class="validation"></div>
</div>
<div class="col-lg-12 form-group">
<label for="address">Location (Address)</label>
<input type="text" class="form-control" name="address" id="address" />
<div class="validation"></div>
</div>
<div class="col-lg-12 form-group">
<label for="project">Select Project / Service</label>
<select type="text" class="form-control" name="project" id="project">
<option selected value="">Select Project</option>
<option value="Emergency HVAC Service">Emergency HVAC Service</option>
<option value="Air Conditioner Installation">Air Conditioner Installation</option>
<option value="Air Conditioner Repair">Air Conditioner Repair</option>
<option value="Air Conditioner Replacement">Air Conditioner Replacement</option>
<option value="Duct Repair">Duct Repair</option>
<option value="Duct Replacement">Duct Replacement</option>
<option value="Furnace Repair">Furnace Repair</option>
<option value="HVAC Maintenance">HVAC Maintenance</option>
<option value="Air Duct Cleaning">Air Duct Cleaning</option>
</select>
<div class="validation"></div>
</div>
<div class="col-lg-12 form-group">
<label for="message">Message</label>
<textarea class="form-control" name="message" id="message"></textarea>
<div class="validation"></div>
</div>
<div id="hide-button" class="col-lg-12 text-center">
<button type="submit" class="btn btn-primary">Send Message</button>
</div>
<div class="col-lg-10 offset-lg-1 text-center">
<div id="sendmessage">Your message has been sent. Thank you!</div>
<div id="errormessage">Sorry! Something went wrong. Try again.</div>
</div>
</div>
</form>
Javascript Validation:
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.contactForm').submit(function() {
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (!i.attr('checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
else var str = $(this).serialize();
var action = $(this).attr('action');
if( ! action ) {
action = 'mail/mailer.php';
}
$.ajax({
type: "POST",
url: action,
data: str,
success: function(msg) {
// alert(msg);
if (msg == 'OK') {
$('#hide-button').addClass("hide");
$("#sendmessage").addClass("show");
$("#errormessage").removeClass("show");
$('.contactForm').find("input, textarea").val("");
} else {
$('#hide-button').removeClass("hide");
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
}
}
});
return false;
});
});
Tell me if I need to add my jQuery.
I'm very familiar with html and css but not that much with PHP and Javascript.
It looks like you have client-side validation in the form of some JavaScript/jQuery stuff, but the fact is that you can't trust the client. Client-side validation is there to help the user, but must not be relied on by the server.
Someone can craft a POST request to your form processing PHP script without using a browser at all, so they can send any old data they like. Probably what you're seeing is emails from some crawler bot or similar doing exactly this.
So, you need to add some similar validation logic to your PHP code (which is obviously on the server side, and therefore much more trustworthy than code on the client side). For example, to check the lname field isn't blank, you could do:
if (empty($lname)) {
showErrorPage('Please enter a last name!');
exit; // To halt processing.
}

PHP,jQuery,HTML form with ajax is not working

I'm trying to submit form data to php script with jQuery .post() method,than to receive php script data back and display it on form page,but it doesnt work.Also I'm using jQuery validate plugin for client side validation as well.Here is my code:
Html:
<div class="contact-form">
<button class="contact-close">X</button>
<form method="post" action="formular.php" id="quote-form">
<div id="returned"></div>
<div class="houndred">
<input type="text" name="name" placeholder="Name*" class="input-half" id="name" min-width="2" autofocus required>
<input type="email" name="email" placeholder="Email*" class="input-half" id="email" required>
<input type="text" name="subject" placeholder="Subject" class="input-half" id="subject" required>
<input type="url" name="url" placeholder="Website" class="input-half" id="website">
</div>
<div class="houndred">
<textarea name="message" class="textarea" id="message" placeholder="message*" required></textarea>
<br><p></p>
</div>
<div class="eightytwo">
<button id="quote-button">Send</button>
</div>
<div id="summary"></div>
</form>
</div><!-- .padding-fix -->
<script src="js/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="js/validation.js"></script>
<script src="js/ajaxform.js"></script>
JS for posting:
$(document).ready(function(){
$('form').on('submit', function(event) {
event.preventDefault();
$.post('formular.php', $(this).serialize(), function(data)) {
var dataForm = data;
$("#returned").append(dataForm);
}
});
)};
and PHP:
if(!empty($_POST)) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$url = $_POST['url'];
$message = $_POST['message'];
if(empty($name) || empty($email) || empty($subject) || empty($url) || empty($message)) {
$errors[] = 'All fields are required!';
} else {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valid email address';
}
if(ctype_alpha($name === false)) {
$errors[] = 'Name can only contain letters';
}
if (ctype_alpha($subject === false)) {
$errors[] = 'Subject can only contain letters';
}
if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) === false) {
$errors[] = 'Please enter a valid url address with http in front';
}
if(empty($message)) {
$errors[] = 'Please enter a message';
}
}
if(!empty($errors)) {
echo '<ul style=\"list-style: circle; color: #f74d4e\">';
foreach($errors as $error) {
echo '<li style=\"color: #f74d4e;\"' . $error . '</li>';
}
echo '</ul>';
}
$send_message = 'From:' . $url . '<br>' . strip_tags(addslashes($message));
if(empty($errors)) {
mail('something#something.com', $subject, $send_message , $email);
echo '<h4 style=\"color: #f74d4e;\">Thank you for contacting me!</h4>';
exit();
}
}
I'm hoping that this makes sense,to me it had,but I'm strugling with it for last couple of hours,still trying to figure out what went wrong,I also tryed posting with $.ajax() and no response.One more thing,form is geting loaded using jquery .load() method to popup box,that is why it is important to me to do it with ajax
From a cursory inspection of your code, it seems that you have added an extra closing parentheses in this line, like so: function(data))
$.post('formular.php', $(this).serialize(), function(data)) {
try
$.post('formular.php', $(this).serialize(), function(data) {
instead
HTH

Javascript is hanging up and takes almost 2 minutes to process form

I have a form up on http://coreelectric.us/contact.php that takes 2 minutes to process. On my localhost it is instantaneous. However, when I put the site live it takes forever. Here is the code in the form itself...
<form action="" method="post" class="form-content" id="contact-form" >
<div class="form-container">
<div id="thanks">Your email was sent successfully. Thank you, we will contact you soon.</div>
<div class="input-form">
<div class="input-left">
<label>*First Name :</label>
<input id="fname" type="text" name="fname" placeholder="Enter your first name" />
</div>
<div class="input-right">
<label>*Last Name :</label>
<input id="lname" type="text" name="lname" placeholder="Enter your last name" />
</div>
<div class="clearfix"></div>
</div>
<div class="input-form">
<div class="input-left">
<label>*Email :</label>
<input id="email" type="text" name="email" placeholder="Enter your valid email address " />
</div>
<div class="input-right">
<label>Phone Number :</label>
<input id="phone" type="text" name="phone" placeholder="Enter your phone only digit" />
</div>
<div class="clearfix"></div>
</div>
<div class="input-form">
<label>*Subject :</label>
<input id="subject" type="text" name="subject" placeholder="Subject"/>
<div class="clearfix"></div>
</div>
<div class="input-form">
<label>*Message :</label>
<textarea id="message" name="message" rows="10" placeholder="Enter your message here"></textarea>
</div>
<div class="input-form">
<label>*You must authenticate:</label>
<div style="float: left;" class="g-recaptcha" id="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" data-callback="onReturnCallback" data-theme="light"></div>
</div>
<input type="submit" style="float: right;" class="btn st-btn btn-rounded btn-primary" value="Submit" />
<div class="error-msg"></div>
</div>
</form>
The javascript being used to process it is...
<script>
document.getElementById('phone').addEventListener('input', function (evt) {
evt.target.value = evt.target.value.replace(/\D/g, '');
});
$(document).on("keyup", "input.error", function(){
phone=$('#phone').val();
if($.isNumeric(phone)){
$('#phone').removeClass("error");
}
});
$(document).ready(function(){
$('#contact-form').submit(function(){
$('#contact-form .error').removeClass('error');
$('#contact-form .error-msg').hide()
form = true;
elm = $(this);
fname = $('#fname').val();
lname = $('#lname').val();
howhear = $('#how_hear').val();
state = $('#state').val();
street = $('#street').val();
city = $('#city').val();
zip = $('#zcode').val();
subject = $('#subject').val();
address = $('#address').val();
email = $('#email').val();
phone = $('#phone').val();
message = $('#message').val();
email_regex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if( email == ''){
$('#email').addClass('error');
form = false;
}else if(email_regex.test(email) == false){
$('#email').addClass('error');
form = false;
}
if(fname==''){
$('#fname').addClass('error');
form = false;
}
if(lname==''){
$('#lname').addClass('error');
form = false;
}
if(subject==''){
$('#subject').addClass('error');
form = false;
}
if(phone==''){
$('#phone').addClass('error');
form = false;
}
if(howhear==''){
$('#how_hear').addClass('error');
form = false;
}
if(state==''){
$('#state').addClass('error');
form = false;
}
if(street==''){
$('#street').addClass('error');
form = false;
}
if(zip==''){
$('#zcode').addClass('error');
form = false;
}
if(address==''){
$('#address').addClass('error');
form = false;
}
if(city==''){
$('#city').addClass('error');
form = false;
}
if(howhear==''){
$('#how_hear').addClass('error');
form = false;
}
if(message==''){
$('#message').addClass('error');
form = false;
}
if(grecaptcha.getResponse() ==""){
$('#g-recaptcha').addClass('error');
$('.error-msg').html('*Captcha ').show();
form = false;
}
if(form == false){
$('.error-msg').html('*Please filled correctly highlighted fields').show();
}
if(form){
$.ajax({
url:'email.php',
type:'post',
data: $('#contact-form').serialize(),
success: function(res){
$('#thanks').show();
setTimeout(function() {
$('#thanks').fadeOut('fast');
}, 60000); // <-- time in milliseconds
$('#contact-form')[0].reset();
}
});
}
return false;
});
});
</script>
the process page contains the following...
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$name = $fname." ".$lname;
$street = $_POST['street'];
$city = $_POST['city'];
$zip = $_POST['zcode'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$how_hear = $_POST['how_hear'];
$newsletter = $_POST['newsletter'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$domain = $_SERVER['SERVER_NAME'];
$to = "receiver#mydomain.com, ".$email;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From:".$email . "\r\n";
$headers .= "BCC: myemail#mydomain.com, another#mydomain.com \r\n";
$txt = '<html style="background-color:#68B7F4">'
. '<div style="background-color:#FFF; padding: 10px;"><img
src="http://coreelectric.us/images/logo.png" alt="Core Electric" >
</div>'
. '<div>An email has been received from the contact page at
'.$domain.'. The following information was provided:<br><br></div>'
. '<table width="100%"><tr><td style="text-align: right; width:
15%;">Name: </td><td style="text-align: left; width:
85%;">'.$name.'</td></tr>'
. '<tr><td style="text-align: right; width: 15%;">Phone: </td><td
style="text-align: left; width: 85%;">'.$phone.'</td></tr>'
. '<tr><td style="text-align: right; width: 15%;">Email: </td><td
style="text-align: left; width: 85%;">'.$email.'</td></tr>'
. '<tr><td style="text-align: right; vertical-align: top; width:
15%;">Message: </td><td style="text-align: left; width:
85%;">'.$message.'</td></tr></table>'
. '<br><br>A representative will be in contact with you within 24
hours.'
. '</html>';
mail($to,$subject,$txt,$headers);
I'd truly appreciate any help understanding what could possibly be causing the hangup. It hangs up between these 2 lines of javascript...
data: $('#contact-form').serialize(),
success: function(res){
Thanks in advance
if(form){
console.log(Date.now())
$.ajax({
url:'email.php',
type:'post',
data: $('#contact-form').serialize(),
success: function(res){
console.log(Date.now())
console.log(res)
$('#thanks').show();
setTimeout(function() {
$('#thanks').fadeOut('fast');
}, 60000); // <-- time in milliseconds
$('#contact-form')[0].reset();
},
error: function(error) {
console.log(Date.now())
console.log(error)
}
});
}
and the php
if(mail($to,$subject,$txt,$headers)) {
echo "OK";
} else {
echo "Whoops";
}
By that, you might at least determine where is the problem. Also you might try to remove the if in php and try if error function in javascript won't catch a php error.
I ran my original code on a different server where I'm now running the same form on 3 different sites and it is lightning fast... narrowed it down to some issue with the other server, that i have zero interest in troubleshooting. I believe this one is closed. Thank you for the input.

Perform two task with jQuery and php

I have a form which a user fills in, the data is sent to my email, but I also wanted email to be posted to my mail chimp using api but it's not working at the moment.
Here is my form:
<form method="POST" onsubmit="return false;" id="dealerForm ">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input id="subject" name="subject" value="Dealer partner message" type="hidden">
<input class="form-control" placeholder="Your Name *" id="name" name="name" required="" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Email *" id="email" name="email" required="" type="email">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Phone *" id="phone" name="phone" required="" type="tel">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Dearlership Info *" id="message" name="message" required=""></textarea>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-right">
<button type="submit" class="btn send_msg">Send Message</button>
</div>
</div>
</form>
Here is my php with mail chimp api and mail send.
<?php
// Email address verification
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
$mailchimp_api_key = 'myapikey'; // enter your MailChimp API Key
// ****
$mailchimp_list_id = 'mylistID'; // enter your MailChimp List ID
// ****
$subscriber_email = addslashes(trim($_POST['email']));
if(!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Not a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$merge_vars = array();
require_once 'mailchimp/php/MailChimp.php';
$MailChimp = new \Drewm\MailChimp($mailchimp_api_key);
$result = $MailChimp->call('lists/subscribe', array(
'id' => $mailchimp_list_id,
'email' => array('email' => $subscriber_email),
'merge_vars' => $merge_vars,
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false,
'send_welcome' => true,
));
if($result == false) {
$array['valid'] = 0;
$array['message'] = 'An error occurred! Please try again later.';
}
else {
$array['valid'] = 1;
$array['message'] = 'Success! Please check your mail.';
}
echo json_encode($array);
}
}
if (isset($_POST["email#mail.com"])) {
$to = 'mail#mail.com';
$subject = $_POST['subject'];
$message = 'Name: '.$_POST["name"].'<br>Email: '.$_POST["email"].'<br>Phone: '.$_POST["phone"].'<br>Message: '.$_POST["message"];
$headers = 'From: ' . $_POST["email"] . "\r\n" .
'Reply-To: ' . $_POST["email"] . "\r\n" .
'Content-type: text/html; charset=iso-8859-1;';
if(mail($to, $subject, $message, $headers)){
echo "New record created successfully";
}
}
?>
While my JQuery code:
$("#dealerForm").on("submit", function(){
//debugger;
$.ajax({
type: 'POST',
var url;
url: "contact/dealer.php",
data: $("#dealerForm").serialize()
}).done(function (data) {
//debugger;
console.log(data);
window.location.href = "https://example.com/Thank%20You.html";
});
$("#dealerForm")[0].reset();
return false;
});
Thanks for your comment and your help.
Before mail-chimp fix I think you need to fix followings:
You don't need to use onsubmit="return false;" in form declaration. You already returned false in jQuery onsubmit. And also remove space from form ID name. So, your form declaration can be like <form method="POST" id="dealerForm">
Remove var url; from ajax
Now debug email/mailchimp code in dealer.php.

Categories

Resources