I have a div with form fields in it including multiple attachments in my HTML. However, I am not sure how to recode the following to allow for zero to many attachments, and not sure about the PHPMailer part. Here is the Ajax part I've got so far. Is this part at least correct? What about sendContactFormEmail.php
? Do I have to use the FormData interface?
<!-- 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
post_data = {
'form_firstname' : $('input[name=form_firstname]').val(),
'form_lastname' : $('input[name=form_lastname]').val(),
'form_address' : $('input[name=form_address]').val(),
'form_city' : $('input[name=form_city]').val(),
'form_email' : $('input[name=form_email]').val(),
'form_phone' : $('input[name=form_phone]').val(),
'form_attachment' : $('input[name=form_attachment]').val(),
'form_message' : $('textarea[name=form_message]').val(),
};
// Ajax post data to server
$.post('mail/sendContactFormEmail.php', post_data, 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();
}, 'json');
}
});
// reset border on entering characters in form fields
$(matchFormFields).keyup(function() {
$(this).css('border-color', '');
$(matchContactSubmitResult).slideUp();
});
});
</script>