Reputation: 3388
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 = "[email protected]";
$from_email = "[email protected]";
$replyTo_email = "[email protected]";
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);
}
}
Upvotes: 2
Views: 826
Reputation: 6773
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);
Upvotes: 0
Reputation: 775
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>
Upvotes: 2