$_POST[] not catching HTML form input - javascript

I have a strange problem, I am passing data from an email form (HTML5) to ajax/JSON and returning false so the page does not redirect to the php script after the submit button is pressed.
If I put commas seperating each data param ($email, $name, $message), only 'name' and 'email' get passed to $_POST[], leaving out the value of$message.
However if there are no commas between the params all the inputs are caught by $_POST[].
For example (with commas): (does not redirect to php script but $message value is not caught in $_POST[])
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',{
name: $('input[name=name]').val(),
email: $('input[name=email]').val(),
message: $('input[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false;
});
Output:
$name=foo
$email=bar
$message=null
Page returns false
(without commas): (redirects to php script but $message value is caught in $_POST[])
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',{
name: $('input[name=name]').val()
email: $('input[name=email]').val()
message: $('input[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false; (does not redirect to `php`)
});
Output:
$name=foo
$email=bar
$message=bar
HTML Form:
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="Scripts/php/sendemail.php">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email address">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Message"></textarea>
</div>
<div class="form-group">
<button type="submit" id="submit" class="btn btn-danger btn-lg">
Send Message
</button>
</div>
</div>
</div>
</form>
JS for form:
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',
{name: $('input[name=name]').val(),
email: $('input[name=email]').val(),
message: $('input[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false;
});
PHP handler:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent! Thankyou :)'
);
$name = $_POST['name'];
$email = $_POST['email'];
$subject = 'query';
$message = $_POST['message'];
$email_from = $email;
$email_to = 'keilcarpenter01#gmail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = mail($email_to, $subject, $body, 'From: visitor');
echo json_encode($status);
#start buffering (all activity to the buffer)
ob_start() ;
# dumps to buffer
var_dump($_POST) ;
# dump buffered $classvar to $outStringVar
$outStringVar = ob_get_contents() ;
# open your file with append, read, write perms
# (be sure to check your file perms)
$fp=fopen('dmp.txt','a+');
# write output to file & close it
fwrite($fp, $outStringVar );
fclose($fp);
# clean the buffer & stop buffering output
ob_end_clean() ;
die;
In this case how does the comma seperatores determine what input by form gets caught by $_POST[]?

You have to change the jquery for get value of textarea, try following code for that :-
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',
{name: $('input[name=name]').val(),
email: $('input[name=email]').val(),
message: $('textarea[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false;
});
It may help you.

Use:
message: $('textarea[name=message]').val()

Related

Send Form data in Email using PHP without refreshing the page

I have a contact section in my website. I want when a user submit the form all the data should be sent in email plus the page don't reload.
My form:
<label for="name">Name:</label>
<input type="text" class="form-control" name="name" id="name" >
</div>
<div class="form-group">
<label for="email">E-Mail:</label>
<input type="email" class="form-control" name="email" id="email" >
</div>
<div class="form-group">
<label for="mobile">Mobile Number:</label>
<input type="text" class="form-control" name="mobile" id="mobile">
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" rows="5" name="message" id="message"></textarea>
</div>
<button type="submit" id="send" class="btn btn-primary" style="width: 100%" name="form_submit">Send Message</button>
Javascript
$(document).ready(function(){
$('#send').click(function(){
var name = $('#name').val();
var email = $('#email').val();
var mobile = $('#mobile').val();
var message = $('#message').val();
var varData = 'name=' + name + '&email=' + email + '&mobile=' + mobile + '&message=' + message;
$.ajax({
type: 'POST',
url: 'process.php',
data: varData,
success: function() {
alert("message sent");
}
});
});
});
</script>
Process.php
if (isset( $_POST['form_submit'] ) ) {
// Do processing here.
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$message = $_POST['message'];
if ($name == '' || $email == '' || $mobile=='' || $message=='')
{
echo "<script> alert('please fill the field');
</script>";
exit;
}
elseif ($_POST["email"]<>'') {
$ToEmail = 'email#gmail.com';
$EmailSubject = 'Website Contact form';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "Name: ".$_POST["name"]."<br><br>";
$MESSAGE_BODY .= "email: ".$_POST["email"]."<br>";
$MESSAGE_BODY .= "mobile: ".nl2br($_POST["mobile"])."<br>";
$MESSAGE_BODY .= "message: ".nl2br($_POST["message"])."";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
echo "<script> alert('mail sent')
</script>";
exit;
} else{
echo "<script> alert ('there is some problem');</script>";
};
}
?>
The problem is the form is not using the code mentioned in "process.php"
How can I ensure the form data is sent in email? I have searched the previous answers but couldn't fix this.

Jquery empty results

Problem
I tried after submitting the form not redirect to email php. For that I used ajax and its somehow working however it's gives back empty result. I have problem with javascript but thats enough difficult to find for my beginner level. I tested to send email without ajax and it sending normally. But redirecting to empty page email.php
HTML
<form method="POST" id="myForm" data-toggle="validator" action="email.php">
<h2 class="section-heading">Свяжитесь с нами:</h2>
<div class="form-group">
<label for="exampleInputEmail1">Имя:</label>
<input style="background:none;" id="firstName" name="firtname" class="form-control" placeholder="Имя" required>
<p id="p1"></p>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Тема:</label>
<input style="background:none;" id="subjectTheme" name="subject" class="form-control" placeholder="Тема" required>
<p id="p2"></p>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Электронная почта:</label>
<input style="background:none;" type="email" id="email" name="email" class="form-control" placeholder="Электронная почта" required>
<p class="help-block with-errors"></p>
</div>
<div class="form-group">
<label>Сообщение:</label>
<textarea style="background:none;" name="message" class="form-control" rows="3"></textarea>
</div>
<input type="submit" id="sendButton" class="btn btn-default"/>
</form>
Javascript
$('#myForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'email.php'
});
$('#myForm')[0].reset();
alert("Success!");
})
PHP
<?php
$to = 'test#mail.ru'; // Replace with your email
$subject = $_POST['subject']; // Replace with your $subject
$headers = 'From: ' . $_POST['email'];
$message = 'Имя: ' . $_POST['firtname'] . "\n" .
'Электронная почта: ' . $_POST['email'] . "\n" .
'Тема: ' . $_POST['subject'] . "\n" .
'Сообщение: ' . $_POST['message'];
mail($to, $subject, $message, $headers);
?>
You need to pass the informations through AJAX. And reset your form on AJAX success. You didn't do that now.
Should look like this:
$('#myForm').submit(function(e) {
e.preventDefault();
var firstname = $('#firstName').val();
var subject = $('#subjectTheme').val();
var email = $('#email').val();
var message = $('#message').val();
$.ajax({
type: 'POST',
url: 'email.php',
data: {firstname: firstname, subject: subject, email: email, message: message },
success: function(){
$('#myForm')[0].reset();
alert("Success!");
}
});
})
You need to pass the content of the form and move the alert and reset to the callback:
$('#myForm').on("submit",function(e) {
e.preventDefault();
$.post(
$(this).attr("action"),
$(this).serialize(),
function(response) {
alert("success");
$('#myForm')[0].reset();
}
);
});
Your email.php file should send a status message to your ajax based on mail is sent or not. You should send your form data to email.php file.
your script
$('#myForm').on("submit",function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'email.php',
data: $('#myForm').serialize(),
success: function(data) {
if(data == 'success') {
alert('mail sent success');
$('#myForm')[0].reset();
} else {
alert('failed');
}
}
});
your PHP
<?php
...
...
if(mail($to, $subject, $message, $headers)) {
$status = 'success';
} else {
$status = 'failed';
}
die($status);
?>

Email Form: $_POST is empty after form submit

I've been all over the forums. The general reason this doesn't work is that you need a NAME attribute, not an ID. I have a name attribute and I still get empty $_POST fields on submit. I'm a beginner and have been at this for 6 hours trying to figure it out. It's probablly something simple. Please help.
I got this free template off ShapeBootstrap: https://shapebootstrap.net/item/1524963-evento-free-music-event-template
My html:
<form action="sendemail.php" method="post" name="contact-form" class="contact-form" id="main-contact-form">
<div class="form-group">
<input name="name" type="text" id="name" required="required" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control" required="required" placeholder="Email ID">
</div>
<div class="form-group">
<textarea name="message" id="message" required class="form-control" rows="10" placeholder="Enter your message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary pull-right">Send</button>
</div>
<div> </div>
</form>
My php:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you'
);
$name = ($_POST["name"]);
$email = ($_POST['email']);
$subject = "Website Message";
$message = ($_POST['message']);
$email_from = $email;
$email_to = 'adam.wilson45#yahoo.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
JavaScript:
// Contact form validation
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
$( window ).resize(function() {
menuToggle();
});
$('.main-nav ul').onePageNav({
currentClass: 'active',
changeHash: false,
scrollSpeed: 900,
scrollOffset: 0,
scrollThreshold: 0.3,
filter: ':not(.no-scroll)'
});
});
Thank you so much in advanced!
You aren't passing any data in your $.post script.
Change $.post($(this).attr('action'), function(data) { to $.post($(this).attr('action'), form.serialize(), function(data) {. The form.serialize() bit passes an object of your form data to the PHP script.
See http://api.jquery.com/jquery.post/ for more info.
THANK YOU #putvande ! Your answer pointed me in the right direction! Adding the form.serialize was close. We needed to add $this. right before it. I wish I talked to you 8hrs ago.
Answer:
Change
$.post($(this).attr('action'), function(data) {
to
$.post($(this).attr('action'), $this.serialize(), function(data) {

Website contact form not receiving messages

Very new html and website developer and unsure why my current contact box is not working. I'm hosting it my own website and when I do attempt to send I get a message sent response but the emails are never received.
I have't eliminated the email hosting being broken by using multiple email addresses to send and receive from but have been unable to get find the source of the problem.
See relevant code bellow
main.js
// Contact form
var form = $('#main-contact-form');
form.submit(function (event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function () {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function (data) {
form_status.html('<p class="text-success">Thank you for contact us. As early as possible we will contact you</p>').delay(3000).fadeOut();
});
});
sendemail.php
<?php
$name = #trim(stripslashes($_POST['name']));
$from = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['name']));
$message = #trim(stripslashes($_POST['message']));
$to = '\\myemailaddress//';
$headers = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: {$name} <{$from}>";
$headers[] = "Reply-To: <{$from}>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();
mail($to, $subject, $message, $headers);
die;
index.html
<div class="col-md-8 col-sm-12">
<div class="contact-form bottom">
<h2>Send a message</h2>
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email Id">
</div>
<div class="form-group">
<textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Your text here"></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-submit" value="Submit">
</div>
</form>
</div>
</div>
Thanks you in advance!
Next issue is you aren't sending any data with your ajax. Using $(formSelector).serialize() simplifies gathering the data
$.ajax({
url: $(this).attr('action'),
//serialize form data and include it with request
data: form.serialize(),
beforeSend: function () {
...
}
}).done(function (data) {
....
});
Currently if you did print_r($_POST); in your php you would see it is empty
After work from #charlietfl answer. Changing the type and url seemed to fix it.
Working code underneath :
main.js:
var form = $('#main-contact-form').serialize();
form.submit(function (event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
type: 'POST',
dataType: "json",
beforeSend: function () {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function (data) {
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
and my .php
<?php
header('Content-type: ');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = '\\myemail//';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;

PHP, jQuery, Ajax, send HTML input fields with attachment field code not working

I am trying to send an email with an optional attachment when a button is clicked and display the results above the form fields. I have put together the following code, but it is not working (nothing happens when I click the submit button; would like to create a fiddle but JSFiddle does not accept PHP code):
Here is the HTML:
<div id="contactSubmitResult"></div>
<div id="contactSubmitResult"></div>
<div id="contactForm">
<div class="col1">
<label for="form_firstname">Firstname <span class="required">*</span></label>
<input type="text" id="form_firstname" name="form_firstname" value="" required />
</div>
<div class="col2">
<label for="form_lastname">Lastname <span class="required">*</span></label>
<input type="text" id="form_lastname" name="form_lastname" value="" required />
</div>
<div class="col1">
<label for="form_address">Address</label>
<input type="text" id="form_address" name="form_address" value="" />
</div>
<div class="col2">
<label for="form_city">City</label>
<input type="text" id="form_city" name="form_city" value="" />
</div>
<div class="col1">
<label for="form_email">Email <span class="required">*</span></label>
<input type="email" id="form_email" name="form_email" value="" required />
</div>
<div class="col2">
<label for="form_phone">Phone <span class="required">*</span></label>
<input type="tel" id="form_phone" name="form_phone" value="" required />
</div>
<div class="col12">
<label for="form_attachment">Add Attachment</label>
<input type="file" id="form_attachment" name="form_attachment" />
</div>
<div class="col12">
<label for="form_message">Message <span class="required">*</span></label>
<textarea id="form_message" name="form_message" required></textarea>
</div>
<div class="col12">
<input type="submit" id="form_send" value="Send" formnovalidate="formnovalidate" />
</div>
</div>
Here is the JavaScript:
<script type="text/javascript" src="http://jdoe.com/js/jquery-1.11.1.min.js"></script>
<!-- validate and submit form input -->
<script type="text/javascript">
$(document).ready(function() {
matchFormFields = "#contactForm input[required], #contactForm textarea[required]";
matchContactSubmitResult = "#contactSubmitResult";
errorColor = 'red';
$("#form_send").click(function() {
var formIsValid = true;
// loop through each field and change border color to red for invalid fields
$(matchFormFields).each(function() {
$(this).css('border-color', '');
// check whether field is empty
if(!$.trim($(this).val())) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
// check whether email is valid
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
});
// submit data to server if form field contents are valid
if (formIsValid) {
// retrieve input field values to be sent to server
var post_data = new FormData();
post_data.append('form_firstname', $('input[name=form_firstname]').val());
post_data.append('form_lastname', $('input[name=form_lastname]').val());
post_data.append('form_address', $('input[name=form_address]').val());
post_data.append('form_city', $('input[name=form_city]').val());
post_data.append('form_email', $('input[name=form_email]').val());
post_data.append('form_phone', $('input[name=form_phone]').val());
post_data.append('form_attachment', $('input[name=form_attachment]')[0].files[0]);
post_data.append('form_message', $('textarea[name=form_message]').val());
// Ajax post data to server
$.ajax({
url: 'http://jdoe.com/sendContactFormEmail.php',
data: post_data,
contentType: false,
processData: false,
type: 'POST',
dataType: 'json',
success: function(response) {
if (response.type == 'error') { // load json data from server and output message
output = '<div class="error">' + response.text + '</div>';
} else {
output = '<div class="success">' + response.text + '</div>';
// reset values in all form fields
$(matchFormFields).val('');
}
// display an animation with the form submission results
$(matchContactSubmitResult).hide().html(output).slideDown();
}
});
}
});
// reset border on entering characters in form fields
$(matchFormFields).keyup(function() {
$(this).css('border-color', '');
$(matchContactSubmitResult).slideUp();
});
});
</script>
Here is the PHP code which receives the jQuery AJAX POST request:
<?php
//$output = json_encode(array('type'=>'error', 'text' => 'Yes'));
//die($output);
include("settings.php");
$boundaryString = "generateboundaryfromthis";
$to_email = "jdoe#gmail.com";
$from_email = "noreply#jdoe.com";
$replyTo_email = "noreply#jdoe.com";
if (isset($_POST)) {
// check whether this is an ajax request, exit if not
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array(
'type' =>' error',
'text' => 'Ajax POST request expected.'
));
die($output); //exit script outputting json data
}
// retrieve sanitized input data
$form_firstname = filter_var($_POST["form_firstname"], FILTER_SANITIZE_STRING);
$form_lastname = filter_var($_POST["form_lastname"], FILTER_SANITIZE_STRING);
$form_address = filter_var($_POST["form_address"], FILTER_SANITIZE_STRING);
$form_city = filter_var($_POST["form_city"], FILTER_SANITIZE_STRING);
$form_email = filter_var($_POST["form_email"], FILTER_SANITIZE_EMAIL);
$form_phone = filter_var($_POST["form_phone"], FILTER_SANITIZE_NUMBER_INT);
$form_message = filter_var($_POST["form_message"], FILTER_SANITIZE_STRING);
$email_body = <<<EOT
Firstname: $form_firstname
Lastname: $form_lastname
Address: $form_address
City: $form_city
E-mail: $form_email
Phone: $form_phone
Message:
$form_message
EOT;
// retrieve attached file
$hasAttachment = false;
if (isset($_FILES["form_attachment"])) {
$hasAttachment = true;
$fileTmpName = $_FILES["form_attachment"]['tmp_name'];
$fileName = $_FILES["form_attachment"]['name'];
$fileSize = $_FILES["form_attachment"]['size'];
$fileType = $_FILES["form_attachment"]['type'];
$fileError = $_FILES["form_attachment"]['error'];
$handle = fopen($fileTmpName);
$content = fread($handle, $fileSize);
fclose($handle);
$encodedContent = chunk_split(base64_encode($content));
}
if ($hasAttachment) {
// user submitted an attachment
$boundary = md5($boundaryString);
// header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:" . $from_email . "\r\n";
$headers .= "Reply-To: " . $replyTo_email . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
// plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($email_body));
// attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $fileType; name=\"$fileName\"\r\n";
$body .="Content-Disposition: attachment; filename=\"$fileName\"\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encodedContent;
} else {
// user did not submit an attachment
$headers = "From:" . $from_email . "\r\n" .
"Reply-To: " . $replyTo_email . "\n" .
"X-Mailer: PHP/" . phpversion();
$body = $email_body;
}
$mailSentSuccessfully = mail($to_email, $subject, $body, $headers);
if ($mailSentSuccessfully) {
//$output = json_encode(array('type'=>'message', 'text' => $pageSettings->getContents("mailSentSuccess")));
$output = json_encode(array('type'=>'message', 'text' => 'Message sent.'));
die($output);
} else {
//$output = json_encode(array('type'=>'error', 'text' => $pageSettings->getContents("mailSentFailure")));
$output = json_encode(array('type'=>'error', 'text' => 'Error encountered. Message not sent.'));
die($output);
}
}
One problem: you forgot to put a html tag to
matchContactSubmitResult = "#contactSubmitResult";
add
<div id="contactSubmitResult"></div>
Here is snippet. I take the liberty to provide an alternative to success: function(){}, instead I used .done() and .fail() to provide in network or other problems. See here: jQuery.ajax() (I can't test your php code, but your jquery code works)
$(document).ready(function() {
matchFormFields = "#contactForm input[required], #contactForm textarea[required]";
matchContactSubmitResult = "#contactSubmitResult";
errorColor = 'red';
$("#form_send").click(function() {
var formIsValid = true;
// loop through each field and change border color to red for invalid fields
$(matchFormFields).each(function() {
$(this).css('border-color', '');
// check whether field is empty
if(!$.trim($(this).val())) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
// check whether email is valid
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
});
// submit data to server if form field contents are valid
if (formIsValid) {
// retrieve input field values to be sent to server
var post_data = new FormData();
post_data.append('form_firstname', $('input[name=form_firstname]').val());
post_data.append('form_lastname', $('input[name=form_lastname]').val());
post_data.append('form_address', $('input[name=form_address]').val());
post_data.append('form_city', $('input[name=form_city]').val());
post_data.append('form_email', $('input[name=form_email]').val());
post_data.append('form_phone', $('input[name=form_phone]').val());
post_data.append('form_attachment', $('input[name=form_attachment]')[0].files[0]);
post_data.append('form_message', $('textarea[name=form_message]').val());
// Ajax post data to server
$.ajax({
url: 'http://jdoe.com/sendContactFormEmail.php',
data: post_data,
contentType: false,
processData: false,
type: 'POST',
dataType: 'json'
}) .done(function(response) {
if (response.type == 'error') { // load json data from server and output message
output = '<div class="error">' + response.text + '</div>';
} else {
output = '<div class="success">' + response.text + '</div>';
// reset values in all form fields
$(matchFormFields).val('');
}
$(matchContactSubmitResult).hide().html(output).slideDown();
}).
fail( function(response){
output = '<div class="error"> NetWork Problems</div>';
$(matchContactSubmitResult).hide().html(output).slideDown();
});
}
});
// reset border on entering characters in form fields
$(matchFormFields).keyup(function() {
$(this).css('border-color', '');
$(matchContactSubmitResult).slideUp();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="contactForm">
<div class="col1">
<label for="form_firstname">Firstname <span class="required">*</span></label>
<input type="text" id="form_firstname" name="form_firstname" value="" required />
</div>
<div class="col2">
<label for="form_lastname">Lastname <span class="required">*</span></label>
<input type="text" id="form_lastname" name="form_lastname" value="" required />
</div>
<div class="col1">
<label for="form_address">Address</label>
<input type="text" id="form_address" name="form_address" value="" />
</div>
<div class="col2">
<label for="form_city">City</label>
<input type="text" id="form_city" name="form_city" value="" />
</div>
<div class="col1">
<label for="form_email">Email <span class="required">*</span></label>
<input type="email" id="form_email" name="form_email" value="" required />
</div>
<div class="col2">
<label for="form_phone">Phone <span class="required">*</span></label>
<input type="tel" id="form_phone" name="form_phone" value="" required />
</div>
<div class="col12">
<label for="form_attachment">Add Attachment</label>
<input type="file" id="form_attachment" name="form_attachment" />
</div>
<div class="col12">
<label for="form_message">Message <span class="required">*</span></label>
<textarea id="form_message" name="form_message" required></textarea>
</div>
<div class="col12">
<input type="submit" id="form_send" value="Send" formnovalidate="formnovalidate" />
</div>
</div>
<div id="contactSubmitResult"></div>
I've updated my code. There are no errors with the PHP code but when I
try to attach an attachment nothing happens. – John Sonderson
if so i think the problem is here.haven't tested but, this might help :)
var myfile=$('input[name=form_attachment]').val();
//apend the file
post_data.append('form_attachment', myfile);

Categories