PHP/Ajax contact form clear input fields only if success - php

I've a simple working php/ajax contact form with validation. I'd like to clear all fields after VALID submission, so I tried $("#myform")[0].reset(); see in the code below. It clears the form nicely, but the problem is it also clears everything when the validation wasn't successful, which is really annoying.
Here's the HTML:
<form id="myform" method="post" action="sendEmail.php">
<div id="container">
<div id="main">
<p>Name / Company <span>*</span></p>
<input type="text" name="name" id="name" />
<p>Email Address <span>*</span><p>
<input type="text" name="email" id="email" />
<p>Offer / Message <span>*</span></p>
<textarea name="message" id="message" rows="6"></textarea>
<p><input type="submit" name="submit" id="submit" value="Send Request" /></p>
<p><ul id="response" /></p>
</div>
</div>
And the php:
<?php
$name = trim($_POST['name']);
$email = $_POST['email'];
$message = $_POST['message'];
$site_owners_email = 'sample#yahoo.com';
$site_owners_name = 'Joe';
if (strlen($name) < 3) {
$error['name'] = "* Please enter your name.";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "* Please enter a valid email address";
}
if (strlen($message) < 4) {
$error['message'] = "* Please leave an offer / message.";
}
if (!$error) {
require_once('phpMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "Subject";
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Send();
echo "<li class='success'> Thanks for your request!<br> We will respond to you as soon as possible. </li>";
} # end if no error
else {
$response = (isset($error['name'])) ? "<li>" . $error['name'] . "</li> \n" : null;
$response .= (isset($error['email'])) ? "<li>" . $error['email'] . "</li> \n" : null;
$response .= (isset($error['message'])) ? "<li>" . $error['message'] . "</li>" : null;
echo $response;
} # end if there was an error sending
?>
At last, the js:
$(function() {
var paraTag = $('input#submit').parent('p');
$(paraTag).children('input').remove();
$(paraTag).append('<input type="button" name="submit" id="submit" value="Send Request" />');
$('#main input#submit').click(function() {
$('#main').append('<img src="images/ajax-loader.gif" class="loaderIcon" alt="Loading..." />');
var name = $('input#name').val();
var email = $('input#email').val();
var message = $('textarea#message').val();
$.ajax({
type: 'post',
url: 'sendEmail.php',
data: 'name=' + name + '&email=' + email + '&message=' + message,
success: function(results) {
$('#main img.loaderIcon').fadeOut(1000);
$('ul#response').html(results);
$("#myform")[0].reset();
}
}); // end ajax
});
});
I'm new to php and js, so I've pasted all of my code, to be easier for you if i did something wrong. Thanks for your help!

Well, a good idea is returning a JSON object form PHP, so you can check for errors on Javascript.
PHP:
$result = array(
"error" => false,
"html" => null
);
if(!$is_valid){
$result["error"] = true;
$result["html"] = "<b>Error</b>";
}else{
$result["error"] = false;
$result["html"] = "<b>Success</b>";
}
echo json_encode($result);
jQuery
$.ajax({
type: 'post',
url: 'url.php',
data: {/*put a cool data here*/},
dataType : "json", // return a json object
success: function(result) {
if(result.error){
/* On error stuff */
$("body").append(result.html);
}else{
/* On success stuff */
$("body").append(result.html);
}
}
});

Related

Sending an email with ajax and object oriented php best practices

I am building a form to send an email and I want to use Object Oriented Php and Ajax.
I was able to build the PHP backend (variable and function) regardless of Ajax, but I have problems in making the Ajax call because I have not yet understood what are the steps to follow.
My problem is that I don't really understand how the ajax URL works (the call the to PHP file). Should I try to target the function (and how can I do) or should I call the page directly, in which I'm gonna create the json function to output a json file to parse with ajax?
Here's my code:
Footer.php and main.js
$('#contact-form').on('submit',function(e) {
e.preventDefault();
$('.output-message').text('Loading...');
const form = $(this);
const post_url = $(this).attr("action");
console.log(post_url);
$.ajax({
url: post_url,
method: form.attr('method'),
data: form.serialize(),
type:'POST',
success: function(result){
console.log(result);
if (result == 'success'){
$('.output-message').text('Message Sent!');
} else {
$('.output-message').text('Error Sending email!');
}
}
});
return false;
});
<form id="contact-form" name="contact-form" action="Contact.php" method="POST" data-parsley-validate="">
<div class="row">
<div class="col-md-6">
<div class="md-form mb-0">
<input type="text" id="name" name="name" class="form-control" required="">
<label for="name" class="">Your name</label>
</div>
</div>
<div class="col-md-6">
<div class="md-form mb-0">
<input type="email" id="email" name="email" class="form-control" required="">
<label for="email" class="">Your email</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="md-form">
<textarea type="text" id="message" name="message" rows="2" class="form-control md-textarea" required=""></textarea>
<label for="message">Your message</label>
</div>
</div>
</div>
<div class="text-center text-md-right">
<input type="submit" id="submit" class="btn-primary" name="submit" value="Request Info">
<span class="output-message"></span>
</div>
</form>
And the php Class:
Contact.php
<?php
class Contact {
public $name;
public $email;
public $message;
public $admin = 'myemail#email.email';
public $errors;
public function sendMail() {
$errors = "";
if ($this->name == "") {
$errors .= '- You forgot to enter a name!<br />';
}
if ($this->email == "") {
$errors .= '- You forgot to enter an email!<br />';
}
if ($this->message == "") {
$errors .= '- You forgot to enter a message!<br />';
}
if(empty($errors)) {
$contents = "To: $this->name<br />Message: $this->message";
$headers = "From:" . $this->email;
$sendmail = mail($this->admin, $this->message, $contents, $headers);
} else {
echo '<p class=\'message error\'>';
echo '<font color="black">' . $errors . '</font>';
echo '</p><br />';
}
}
}
if(isset($_POST['submit'])) {
$sendMail = new Contact();
$sendMail->name = $_POST['name'];
$sendMail->email = $_POST['email'];
$sendMail->message = $_POST['message'];
$sendMail->sendMail();
}
?>
The javascript part doesn't work, and I'm trying to understand this part:
const post_url = $(this).attr("action");
$.ajax({
url: post_url,
Should I create another function in PHP that will output a JSON file that collects all the variables?
My though is that I'm serializing the URL and then I will send it to the PHP file, but I'm not even able to console.log() the result.
Refactor a little bit :
class Contact
{
public $name;
public $email;
public $message;
public $admin = 'myemail#email.email';
public $errors;
public function sendMail() {
$errors = "";
if ($this->name == "") {
$errors .= '- You forgot to enter a name!<br />';
}
if ($this->email == "") {
$errors .= '- You forgot to enter an email!<br />';
}
if ($this->message == "") {
$errors .= '- You forgot to enter a message!<br />';
}
if(empty($errors)) {
$contents = "To: $this->name<br />Message: $this->message";
$headers = "From:" . $this->email;
$sendmail = mail($this->admin, $this->message, $contents, $headers);
} else {
throw new Exception($errors, 400);
}
}
}
if(isset($_POST['submit'])) {
$sendMail = new Contact();
$sendMail->name = $_POST['name'];
$sendMail->email = $_POST['email'];
$sendMail->message = $_POST['message'];
header('Content-Type: aaplication/json');
try {
$sendMail->sendMail();
echo json_encode(array('success' => 'success'));
} catch (Exception $e) {
header ('HTTP/1.1 400 Bad Request')
$errors = array('error' => $e->getMessage);
echo json_encode($errors);
}
}
I've made it return the string instead of echoing in the class, and I've thrown an exception on an error. Also, since we are sending to JS I made it return JSON.
Lastly, change the JS here:
$.ajax({
url: post_url,
method: form.attr('method'),
data: form.serialize(),
type:'POST',
success: function(result){
console.log(result);
$('.output-message').text('Message Sent!');
}
error: function(result) {
console.log(result);
$('.output-message').text('Error Sending email!');
}
});
JS will check a 200, so know if it is success. Since you now send a 400 on error, the error function will trigger! Give that a try :-)

Send multiple contact form from one page via AJAX

I have 3 contact form in one page ( Header, Body, Footer ). The code works correctly if sent from one form. I want to use one AJAX request for all forms. That is, when you click on the submit button, so that the code checks if this form then send data to php. How can i do it right? I use the hasClass () method of jquery, but I have errors in the console
HTML:
Footer Form
<form id="contact-form1" method="POST" class="d-flex form">
<input type="text" class="simple-input" id="name" placeholder="Name">
<input type="text" class="simple-input" id="email" placeholder="Email address">
<textarea class="quession-input" id="msg" placeholder="Your question"></textarea>
<div class="checkboks custom-sq">
<input type="checkbox" class="checked-checkbox" name="myCheckboxes[]" id="box1" checked="checked" value="true" />
<label for="box1" class="checkboks-text"><?php echo the_field('checkbox_text', 'option'); ?></label>
</div>
<button type="submit" id="submit" class="danger-btn submit1"><?php echo the_field('btn_send', 'option'); ?></button>
</form>
Another Form
<form id="contact-form" method="POST" class="d-flex form">
<input type="text" class="simple-input" id="hy_name" placeholder="Name">
<input type="text" class="simple-input" id="hy_email" placeholder="Email address">
<textarea class="quession-input" id="hy_msg" placeholder="Your question"></textarea>
<div class="checkboks custom-sq">
<input type="checkbox" id="box3" class="checked-checkbox" checked="checked" />
<label for="box3" class="checkboks-text"><?php echo the_field('checkbox_text', 'option'); ?></label>
</div>
<button type="submit" id="submit" class="danger-btn hy-submit submit2"><?php echo the_field('btn_send', 'option'); ?></button>
</form>
jQuery:
jQuery('#submit').on('click', function(e) {
e.preventDefault();
if(e.hasClass('submit1')) {
var name = jQuery('#name').val();
var email = jQuery('#email').val();
var msg = jQuery('#msg').val();
var subj = jQuery('#subj').val();
var data = "action=send_email&name=" + name + "&email=" + email + "&msg=" + msg + "&subj=" + subj + "&myCheckboxes=" + choice,
} elseif (e.hasClass('submit2')) {
var hy_name = jQuery('#hy_name').val();
var hy_email = jQuery('#hy_email').val();
var hy_msg = jQuery('#hy_msg').val();
var data = "action=send_email&name=" + hy_name + "&email=" + hy_email + "&msg=" + hy_msg + "&myCheckboxes=" + choice,
}
validateEmail(email);
if (msg == '' || email == '' || validateEmail(jQuery('#email').val()) == false) {
validateEmail(email);
validateText(jQuery('#msg'));
validateText(jQuery('#name'));
return false;
}
var chkElem = document.getElementsByName("myCheckboxes[]");
var choice ="";
for(var i=0; i< chkElem.length; i++)
{
if(chkElem[i].checked)
choice = choice + chkElem[i].value;
}
jQuery.ajax({
type: "post",
url: "/wp-admin/admin-ajax.php",
data: data;
success: function (response) {
jQuery('#contact-form input').val('');
jQuery('#contact-form textarea').val('');
jQuery('.submit').text('Done!');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
});
PHP:
add_action('wp_ajax_nopriv_send_email', 'send_email');
add_action('wp_ajax_send_email', 'send_email');
function send_email() {
$checkbox = $_POST['myCheckboxes'];
if (isset($checkbox)) {
echo $checkbox;
}
$headers = 'Content-Type: text/html; charset="utf-8"';
$name = $_POST['name'];
$hy_name = $_POST['hy_name'];
$from = 'contact#xelon.ch';
$to = 'yaver.mammadov#gmail.com';
$email = $_POST['email'];
$hy_email = $_POST['hy_email'];
$msg = $_POST['msg'];
$hy_msg = $_POST['hy_msg'];
$subject = 'Footer form: ' . $_POST['email'];
$message .= (!empty($name)) ? '<p><strong>User Name</strong> : ' . $name .' </p>' : '';
$message .= (!empty($email)) ? '<p><strong>User Email</strong> : '. $email .'</p>' : '';
$message .= (!empty($msg)) ? '<p><strong>User Message</strong> : '.$msg .'</p>' : '';
$message .= (!empty($checkbox)) ? '<p><strong>Checkboxs</strong> : '.$checkbox .'</p>' : '';
$message .= '</body></html>';
echo mail($to, $subject, $message, $headers);
return $msg;
die();
}
You can use method serialize(), and use a class to identifique buttons submit. Using two identical ids on one page is not good practice.
If you use the class .submit per example in each button submit:
$('.submit').on('click', function(e) {
e.preventDefault();
var data = $(this).closest('form').serialize();
[...]
}

Change the color of messages when submitting a form using Ajax

Someone can help me? There is a working form for sending messages to email.
<form enctype="multipart/form-data" role="form" id="form" method="post" action="handler.php">
<div class="form-row">
<div class="form-group col-sm-6">
<label for="name" class="nameForInput">Name:</label>
<input type="text" name="name" class="form-control" id="name" placeholder="Enter name" >
</div>
<div class="form-group col-sm-6">
<label for="email" class="nameForInput">Email:</label>
<input type="mail" name="email" class="form-control" id="email" placeholder="Enter email" >
</div>
</div>
<div class="form-group">
<label for="phone" class="nameForInput">Phone:</label>
<input class="form-control phone" name="phone" type="text" placeholder="+3 (000) 000-00-00" >
</div>
<div class="form-group">
<label for="message" class="nameForInput">Message:</label>
<textarea id="message" class="form-control" name="message" rows="5"placeholder="Enter your message" ></textarea>
</div>
<div class="form-group">
<label for="myfile" class="file-label left">
<img src="img/upload.svg" alt="">
<p class="amount">To attach files</p>
</label>
<input type="file" class="my" id="myfile" name="myfile[]" multiple>
</div>
<div class="form-group">
<input id="check" name="check" checked type="checkbox">
<span class="check-text">I confirm my consent to the processing of personal data</span>
</div>
<button type="submit" class="btn btn-success btn-lg">Send</button>
<div class="result">
<span id="answer"></span>
<span id="loader"><img src="img/loader.gif" alt=""></span>
</div>
</form>
ajax:
var form = $('#form'),
button = $('.btn'),
answer = $('#answer'),
loader = $('#loader');
$.ajax({
url: 'handler.php',
type: 'POST',
contentType: false,
processData: false,
data: new FormData(this),
beforeSend: function() {
answer.empty();
button.attr('disabled', true).css('margin-bottom', '20px');
loader.fadeIn();
},
success: function(result) {
loader.fadeOut(300, function() {
answer.text(result);
});
form[0].reset();
button.attr('disabled', false);
},
error: function() {
loader.fadeOut(300, function() {
answer.text('An error occurred! Try later.');
});
button.attr('disabled', false);
}
});
});
});
ContactMailer.php:
<?php
class ContactMailer
{
/**
* Sender's E-mail
* #var string
*/
private static $emailFrom = 'somemail#mail.com';
/**
* Recipient's E-mail
* #var string
*/
private static $emailTo = 'somemail#mail.com';
/**
* Sends an email if the email is sent,
* Returns TRUE, otherwise FALSE.
* #param string $name
* #param string $email
* #param string $phone
* #param string $message
* #return boolean
*/
public static function send($name, $email, $phone, $message)
{
// We form a letter body
$body = "Name: " . $name . "\nE-mail: " . $email . "\nPhone: " . $phone . "\n\nMessage:\n" . $message;
// Create PHPMailer object
$mailer = new PHPMailer(true);
// Connection settings
$mailer->isSMTP();
// Installs the mail server host (Mail.ru: smtp.mail.ru, Google: smtp.gmail.com)
$mailer->Host = 'smtp.mail.com';
// Includes SMTP authorization
$mailer->SMTPAuth = true;
// Entire login or E-mail
$mailer->Username = self::$emailFrom;
// Mailbox Password
$mailer->Password = '';
// Protocol of connection
$mailer->SMTPSecure = '';
// Port for outgoing mail
$mailer->Port = '';
// Establishes coding
$mailer->CharSet = 'UTF-8';
// Sets E-mail and sender name
$mailer->setFrom(self::$emailFrom, $name);
// Adds recipient 's E-mail
$mailer->addAddress(self::$emailTo);
// Control of a HTML-format
$mailer->isHTML(false);
// Letter subject
$mailer->Subject = 'Feedback form completed';
// Main body of the letter
$mailer->Body = $body;
// Send the letter
if ($mailer->send()) {
return true;
}
return false;
}
}
handler.php:
<?php
require_once __DIR__ . '/mailer/Validator.php';
require_once __DIR__ . '/mailer/ContactMailer.php';
if (!Validator::isAjax() || !Validator::isPost()) {
echo 'Access is forbidden!';
exit;
}
$name = isset($_POST['name']) ? trim(strip_tags($_POST['name'])) : null;
$email = isset($_POST['email']) ? trim(strip_tags($_POST['email'])) : null;
$phone = isset($_POST['phone']) ? trim(strip_tags($_POST['phone'])) : null;
$message = isset($_POST['message']) ? trim(strip_tags($_POST['message'])) : null;
//protection against XSS
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
//Issues an error if the download size exceeds the limit set by the server
if($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0)
{ echo "CONTENT SIZE EXCEEDS THE LIMIT";
exit;}
if (empty($name) || empty($email) || empty($phone) || empty($message)) {
echo 'All fields are required.';
exit;
}
if (!Validator::isValidName($name)) {
echo 'Name does not match format (name must contain only letters).';
exit;
}
if (!Validator::isValidEmail($email)) {
echo 'E-mail does not conform to the format.';
exit;
}
if (!Validator::isValidPhone($phone)) {
echo 'Phone doesn\'t match format.';
exit;
}
if (ContactMailer::send($name, $email, $phone, $message)) {
echo htmlspecialchars($name) . ', your message was sent successfully.';
} else {
echo ' An error occurred! Failed to send message.';
}
exit;
?>
css:
#answer {
color: #ff5b5b;
}
Everything works, but all messages are displayed in red because the styles for # answer are set to red. But it is necessary that in case of successful submission of forms messages are displayed in green color, and in case of errors - in red. Tried adding this:
success: function(result) {
loader.fadeOut(300, function() {
if (result === 'ok') {
answer.text(result).addClass('success');
} else {
answer.text(result).addClass('error');
}
});
form[0].reset();
button.attr('disabled', false);
},
css:
.success {
color: #218838;
}
.error {
color: #ff5b5b;
}
but only the class 'error' is always added, and if the submission is successful as well. Also tried in the file handler.php simply stick styles to the message:
if (ContactMailer::send($name, $email, $phone, $message)) {
echo htmlspecialchars($name) . '<span style="color: #218838;">, your message was sent successfully.</span>';
} else {
echo 'An error occurred! Failed to send message.';
}
exit;
but nothing applies, issues just a message along with tags:
'<span style="color: #218838;">, your message was sent successfully.</span>'
Although if you create just some other php file, there the message in echo is displayed in green, does not work in this handler.php file.
Someone can suggest how to properly make the switch in Ajax so that the message is displayed green when successfully sent and why css styles are not applied in handler.php.
It never enters the code for success because result is never set to 'ok' but to a long successful message.
success: function(result) {
loader.fadeOut(300, function() {
if (result.includes('your message was sent successfully')) {
answer.text(result).addClass('success');
} else {
answer.text(result).addClass('error');
}
});
form[0].reset();
button.attr('disabled', false);
},
One more.
ContactMailer:
// Send the letter
if ($mailer->send()) {
return true;
}
return false;
handler.php:
require_once __DIR__ . '/mailer/Validator.php';
require_once __DIR__ . '/mailer/ContactMailer.php';
if (!Validator::isAjax() || !Validator::isPost()) {
$data['error'] = 'Access is forbidden!';
echo json_encode($data);
exit;
}
$data = array();
$name = isset($_POST['name']) ? trim(strip_tags($_POST['name'])) : null;
$email = isset($_POST['email']) ? trim(strip_tags($_POST['email'])) : null;
$phone = isset($_POST['phone']) ? trim(strip_tags($_POST['phone'])) : null;
$message = isset($_POST['message']) ? trim(strip_tags($_POST['message'])) : null;
//protection against XSS
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
//Issues an error if the download size exceeds the limit set by the server
if($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0) {
$data['error'] = "CONTENT SIZE EXCEEDS THE LIMIT";
echo json_encode($data);
exit;
}
if (empty($name) || empty($email) || empty($phone) || empty($message)) {
$data['error'] = 'All fields are required.';
echo json_encode($data);
exit;
}
if (!Validator::isValidName($name)) {
$data['error'] = 'Name does not match format (name must contain only letters).';
echo json_encode($data);
exit;
}
if (!Validator::isValidEmail($email)) {
$data['error'] = 'E-mail does not conform to the format.';
echo json_encode($data);
exit;
}
if (!Validator::isValidPhone($phone)) {
$data['error'] = 'Phone doesn\'t match format.';
echo json_encode($data);
exit;
}
if (ContactMailer::send($name, $email, $phone, $message)) {
$data['success'] = htmlspecialchars($name) . ', your message was sent successfully.';
echo json_encode($data);
} else {
$data['error'] = 'An error occurred! Failed to send message.';
echo json_encode($data);
}
exit;
ajax:
$(function() {
$('#form').on('submit', function(e) {
e.preventDefault();
var form = $('#form'),
button = $('.btn'),
answer = $('#answer'),
loader = $('#loader');
answer.removeClass('error success');
$.ajax({
url: 'handler.php',
type: 'POST',
contentType: false,
processData: false,
dataType: "json",
data: new FormData(this),
beforeSend: function() {
answer.empty();
button.attr('disabled', true).css('margin-bottom', '20px');
loader.fadeIn();
},
success: function(data) {
loader.fadeOut(300, function() {
if (data.error) {
answer.text(data.error).addClass('error');
} else {
answer.text(data.success).addClass('success');
}
});
form[0].reset();
button.attr('disabled', true);
},
error: function() {
loader.fadeOut(300, function() {
answer.text('An error occurred! Try later.').addClass('error');
});
button.attr('disabled', true);
}
});
});
});
In this method in ajax necessarily add dataType: "json".
One more way.
ContactMailer.php:
// Send the letter
if ($mailer->send()) {
return true;
} else {
echo 'no';
return false;
}
handler.php:
if (ContactMailer::send($name, $email, $phone, $message)) {
echo 'yes';
} else {
echo 'An error occurred! Failed to send message.';
}
exit;
ajax:
success: function(data) {
loader.fadeOut(300, function() {
if (data === "yes") {
answer.text("Your message was sent successfully.").addClass('success');
} else {
answer.text(data).addClass('error');
}
});
form[0].reset();
button.attr('disabled', true);
},
To switch correctly before calling ajax, we also delete the answer. removeClass ('error success') class as in the example above, otherwise two classes will be added to the answer at once.

How to validate captcha field code?

I am trying to validate a captcha code field so if the code they enter is correct it will take them to a thank you page with the download link, but if the security code they entered is incorrect then they will see a sorry message and to return back to previous page.
The issue I am facing is when I enter the captcha into this field and click submit the data is always no.
My form is a as follows:
<form action="" name="downloadform" id="downloadform" class="downloadform" method="post">
<div class="field">
<input name="name" type="text" id="name" class="input name" placeholder="Name..." />
</div>
<div class="field">
<input name="company" type="text" id="company" class="input company" placeholder="Company..." />
</div>
<div class="field">
<input name="tel" type="text" id="tel" class="input tel" placeholder="Telephone..." />
</div>
<div class="field">
<input name="email" type="text" id="email" class="input email" placeholder="Email Address..." />
</div>
<div class="field">
<img src="/CaptchaSecurityImages.php" alt="Captcha" class="captcha" />
<input type="text" name="sec_code" id="sec_code" class="input sec_code" placeholder="Please enter the characters above" />
</div>
<div class="field">
<div class="medium secondary btn"><input type="submit" name="Submit2" value="Send Request" class="btn" id="downloadbtn" /></div>
<input type="hidden" name="product" id="product" class="product" value="<?php echo $page[3]; ?>" />
</div>
</form>
My ajax form file looks like this:
$(function() {
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$("#downloadbtn").click(function() {
var name = $("#name").val();
var company = $("#company").val();
var tel = $("#tel").val();
var email = $("#email").val();
var product = $("#product").val();
var sec_code = $("#sec_code").val();
if (name == "") {
$("#name").focus();
$("#name").val("");
$("#name").css({background:"#b72a18", color:"#fff"});
return false;
}
if (company == "") {
$("#company ").focus();
$("#company ").val("");
$("#company ").css({background:"#b72a18", color:"#fff"});
return false;
}
if (tel == "") {
$("#tel").focus();
$("#tel").val("");
$("#tel").css({background:"#b72a18", color:"#fff"});
return false;
}
if (!filter.test(email)) {
$("#email").focus();
$("#email").val("");
$("#email").css({background:"#b72a18", color:"#fff"});
return false;
}
if (product == "") {
$("#product").focus();
$("#product").val("");
$("#product").css({background:"#b72a18", color:"#fff"});
return false;
}
if (sec_code == "") {
$("#sec_code").focus();
$("#sec_code").val("");
$("#sec_code").css({background:"#b72a18", color:"#fff"});
return false;
}
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>');
var dataString = '&name=' + name + '&tel=' + tel + '&company=' + company + '&email=' + email + '&product=' + product + '&sec_code=' + sec_code + '&type=download';
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/process_download.php",
data: dataString,
datatype: 'json',
success: function(data) {
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>')
.hide()
.fadeIn(1500, function() {});
setTimeout(function ()
{
$(window.location).attr('href', '/process.php?download=' + data.product + '&sec_code=' + data.sec_code);
}, 2000);
}
});
return false;
});
});
Then I have my process download file:
<?php
session_start();
header("Content-type: application/json");
ob_start();
include('inc/connection.php');
$product = $_POST['product'];
$sec_code = $_SESSION['security_code'] == $_POST['sec_code'] ? 'yes' : 'no';
ob_end_clean();
$data = array('product'=>$product,'sec_code'=>$sec_code);
print json_encode($data);
die();
?>
Then the final process:
<?php
session_start();
include('inc/connection.php');
$sec_code = $_GET['sec_code'];
$proddownlink = $_GET['download'];
$proddownl = str_replace("_", " ", $_GET['download']);
$proddownl = ucwords($proddownl);
if ($sec_code == 'no') {
$message = '<p>Security code is wrong. Please click here to return back.</p>';
} else {
$message = '<p>Thank you for downloading ' . $proddownl . ' Data Sheet.</p>
<p>Please click here to download ' . $proddownl . ' PDF.</p>';
include_once('inc/connection.php');
include_once('inc/class.phpmailer.php');
$name = $_POST['name'];
$company = $_POST['company'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$product = $_POST['product'];
$sec_code = $_POST['sec_code'];
$type = $_POST['type'];
$bodytext = "<ul>
<li><strong>Name:</strong> $name</li>
<li><strong>Company:</strong> $company</li>
<li><strong>Telephone Number:</strong> $tel</li>
<li><strong>Email Address:</strong> $email</li>
<li><strong>Area of Interest:</strong> $product</li>
</ul>";
$subject = "New Enquiry";
$query = "insert into user_email set name = '$name', email = '$email', tel = '$tel', type = '$type', message = '$bodytext'";
$result = $conn->query($query);
if(!$result) die($conn->error);
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $bodytext;
$mail->From = "sales#fidelitysystems.co.uk";
$mail->FromName = $name;
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
#$mail->AddAddress("sales#fidelitysystems.co.uk");
$mail->AddAddress("craig#arrivaldesign.co.uk");
$mail->IsSMTP();
$mail->SMTPAuth = "true";
$mail->Username = "postmaster#arrivalbusiness.co.uk";
$mail->Password = "edward";
$mail->Host = "mail.arrivalbusiness.co.uk";
$mail->Port = 587;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>

Attaching an uploaded file as an attachment In PHPmailer and Jquery

I have created a web form where people can enter registration information and upload an image to our server. I can get their name, email and message but I can't figure out how to get the uploaded file. I'd like to have the page not reload so that's why I'm using JQuery. It mostly works but I can't get the uploaded file to be recognized in the POST data or the FILES data. The form and processor page are located in the same directory and the image get placed in a subfolder called uploads. Here is what I have so far which does not work for attaching image. I believe the problem is in the JavaScript file where I define the var photoFile = $('#submitForm #photoFile').val(); What is the correct way to declare the uploaded file?
Here's the HTML form:
form action="../inc/sendPhotoEmail.php" name="submitForm" id="submitForm" method="post"
enctype="multipart/form-data">
<label for="submitName">Name <span class="required">*</span></label>
<input name="submitName" type="text" id="submitName" size="35" value="" />
<label for="submitEmail">Email <span class="required">*</span></label>
<input name="submitEmail" type="text" id="submitEmail" size="35" value="" />
<label for="submitMessage">Tell us what you want fixed <span class="required">*</span></label>
<textarea name="submitMessage" id="submitMessage" rows="10" cols="50" ></textarea>
<label for="attach_photo">Attach Your Photo<span class="required"/>*</span></label>
<input type="file" name="photoFile" id="photoFile" accept="image/*"/>
<button class="submit" name="submitFormSubmit" value="Submit">Submit</button>
<span id="image-loader"><img src="images/loader.gif" alt="" /></span>
</form> <!-- Form End -->
<!-- contact-warning -->
<div id="message-warning"></div>
<!-- contact-success -->
<div id="message-success">
<i class="icon-ok"></i>Your message was sent, thank you!<br />
</div>
The javascript:
jQuery(document).ready(function() {
$('form#submitForm button.submit').click(function() {
$('#image-loader').fadeIn();
var submitName = $('#submitForm #submitName').val();
var submitEmail = $('#submitForm #submitEmail').val();
var submitMessage = $('#submitForm #submitMessage').val();
var photoFile = $('#submitForm #photoFile').val();
var data = 'submitName=' + submitName + '&submitEmail=' + submitEmail +
'&submitMessage=' + submitMessage + $photoFile='+ photoFile;
$.ajax({
type: "POST",
url: "inc/sendPhotoEmail.php",
data: data,
success: function(msg) {
// Message was sent
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#submitForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false;
});
And the PHP file:
<?php
require_once('class.phpmailer.php');
$ourEmail = "repair#myemail.net";
$target_dir = "../uploads/";
if($_POST) {
$name = trim(stripslashes($_POST['submitName']));
$email = trim(stripslashes($_POST['submitEmail']));
$emailMessage = trim(stripslashes($_POST['submitMessage']));
$image_attachment = $_POST["photoFile"]; // <---- this doesn't print anything
$targetFile = $target_dir . basename($_FILES["photoFile"]["name"]);
echo "targetFile = ". $targetFile . "<br/>"; // <-- this only prionts the subdirectory
move_uploaded_file($_FILES["photoFile"]["tmp_name"],$target_dir.$_FILES["photoFile"]["name"]);
echo "Uploaded File :".$_FILES["photoFile"]["name"]. "<br/>";
$target_file = $target_dir . basename($_FILES["photoFile"]["name"]);
echo "target_file = ". $target_file . "<br/>";
$mail = new PHPMailer(); //Create a new PHPMailer instance
$mail->isSendmail(); // Set PHPMailer to use the sendmail transport
// Set Message
$mail->setFrom($email, $name); //Set who the message is to be sent from
$mail->addReplyTo("replyto#example.com", "First Last"); //Set an alternative reply-to address
$mail->addAddress($ourEmail, "Figley T. Whitesides"); //Set who the message is to be sent to
$mail->Subject = "Repair Form Submission"; //Set the subject line
$mail->WordWrap = 80;
$mail->msgHTML($emailMessage); //Create message bodies and embed images
$mail->addAttachment($target_file); //Attach an image file
if (!$error) {
//send the message, check for errors
if (!$mail->send()) {
$mail->ErrorInfo;
} else {
$response = "Photo sent!";
} // end if - no validation error
}
else{
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
$response .= (isset($error['attachment'])) ? $error['attachment'] . "<br />" : null;
echo $response;
} // end if - there was a validation error
}
?>
});
You can't upload data and files with one form using ajax, but try this code,
$("form#data").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function() {
// success
});
return false;
});

Categories