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;
});
Related
On every page I have jQuery modal which contains a contact form and which on every page need sent data to different email address. When a form is submitted I need to display successful response using json_encode. Also on every page I use page identifier as $pages_id=1, $pages_id=2, etc., for identify which form is submitted. However, very important, without jQuery file, complete my PHP code it's executed correctly, all data are successfully inserted into database and in Xdebug I also see that code on every line it's executed successfully. But, if I include jQuery file then in Xdebug the value for $pages_id return null. I exactly think at this line of code:
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1,$pages_id);
$dbstmt->execute();
However, below is my complete PHP code:
<?php
// set error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL | E_STRICT);
$fname = $tel = $userMail = $userMessage = $email_address_id = "";
$fname_error = $tel_error = $userMail_error = $userMessage_error = "";
$error=false;
//Load the config file
$dbHost = "secret";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "secret";
$dbCharset = "utf8";
$pdo="";
try{
$dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
$pdo = new PDO($dsn, $dbUser, $dbPassword);
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}catch(PDOException $e){
echo "Connection error: " . $e->getMessage();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['submitOwner'])){
$fname = $_POST['fname'];
$tel = $_POST['tel'];
$userMail = $_POST['userMail'];
$userMessage = $_POST['userMessage'];
if(empty($_POST['fname'])){
$error=true;
$fname_error = "Name and surname cannot be empty!";
}else{
$fname = $_POST['fname'];
if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)){
$fname_error = "Name and surname can only contain letters and spaces!";
}
}
if(empty($_POST['tel'])) {
$tel_error = "Phone number cannot be blank!";
}else{
$tel = $_POST['tel'];
if(!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
$tel_error = "The phone number should contain a minimum of 9 to 15 numbers!";
}
}
if(empty($_POST['userMail'])){
$userMail_error = "Email cannot be blank!";
}else{
$userMail = $_POST['userMail'];
if(!filter_var($userMail, FILTER_VALIDATE_EMAIL)) {
$userMail_error = "Email address is incorrect!";
}
}
if(empty($_POST['userMessage'])) {
$userMessage_error = "The content of the message cannot be empty!";
}else{
$userMessage = $_POST['userMessage'];
if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ0-9 ,.!?\'\"]*$/", $userMessage)){
$userMessage_error = "The content of the message cannot be special characters!";
}
}
if($fname_error == '' && $tel_error == '' && $userMail_error == '' && $userMessage_error == ''){
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'secret';
$mail->SMTPAuth = true;
$mail->Username = 'secret';
$mail->Password = 'secret';
$mail->Port = 465; // 587
$mail->SMTPSecure = 'ssl'; // tls
$mail->WordWrap = 50;
$mail->setFrom('secret#secret.com');
$mail->Subject = "New message from visit-neum.com";
$mail->isHTML(true);
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1,$pages_id);
$dbstmt->execute(); //in Xdebug this line of code return NULL for $pages_id if include jQuery file
$emails_other = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
$jsonData=array();
if(is_array($emails_other) && count($emails_other)>0){
foreach($emails_other as $email_other){
//var_dump($email_other['email_address']);
$mail->addAddress($email_other['email_address']);
$body_other = "<p>Dear {$email_other['owner_name']}, <br>" . "You just received a message from the site <a href='https://www.visit-neum.com'>visit-neum.com</a><br>Details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "<br><strong>E-mail: </strong>" .strtolower($userMail)."<br><strong>Message: </strong>" . $userMessage . "</p>";
$mail->Body = $body_other;
if($mail->send()){
$mail = "INSERT INTO visitneum.contact_owner(fname, tel, userMail, userMessage, email_address_id) VALUES(:fname, :tel, :userMail, :userMessage, :email_address_id)";
$stmt = $pdo->prepare($mail);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'userMail' => $userMail, 'userMessage' => $userMessage, 'email_address_id' => $email_other['email_address_id']]);
// Load AJAX
if($error==false){
$information['response'] = "success";
$information['content'] = "Thanks " . ucwords($fname) . "! Your message has been successfully sent to the owner of property! You will get an answer soon!";
$jsonData[] = $information;
}
}//end if mail send
else{
$information['response'] = "error";
$information['content'] = "An error has occurred! Please try again..." . $mail->ErrorInfo;
$jsonData[]=$information;
}
echo(json_encode($jsonData));
} // end foreach($emails_other as $email_other)
} // end if(is_array($emails_other) && count($emails_other)>0)
} // end if validation
} // end submitOwner
} // end REQUEST METHOD = POST
And below you can see submitHandler for my jQuery file which causes me problem:
submitHandler: function(form){
var formData=jQuery("#contactOwner").serialize();
console.log(formData);
jQuery.ajax({
url: "/inc/FormProcess.php",
type: "post",
dataType: "json",
data: formData,
success:function(jsonData) {
jQuery("#responseOwner").text(jsonData.content);
console.log(jsonData);
error: function (jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
}); // Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} // end submitHandler
And the page which contains contact form is below:
<?php
include_once './inc/FormProcess.php';
?>
<form spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form' name='contactOwner' action='' method='POST'>
<h4 id="responseOwner" class="success">
<!-- This will hold response from the server --></h4>
<fieldset>
<legend>Vaši podaci</legend>
<div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Your name and surname ..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
<div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Your phone number..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->
<div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Your e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope owner_icon" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control -->
<div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Your message..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
</fieldset>
<input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="SENT"/>
</form>
<script defer src="/JS/validateOwner.js"></script>
So, I can not figure out what is the problem and why $pages_id return null when include jQuery file. Also, I was forget to mention that code inside line if(is_array($emails_other) && count($emails_other)>0){ return number 0, so complete seguent code isn't executed, but of course this is normal, because $pages_id is null. However, I hope that somebody understand what is the problem and so, thanks in advance for any kind of help that you can give me.
page_id is null in your script because you dont set it in the script.
So why not just adding an hidden input field in your froms with the page id and then in your PHP code
$page_id = $_POST['pageId'];
i think you did not understood ajax correclty. if you post your data to /inc/FormProcess.php it is not like an include before, where you could create variables first and then include it. AJax is like a sub call to the script. it is like if you would open ONLY this scrirpt provided in URL. so at this point you dont have your variables.
you need to get the variables or send your ajax request NOT to /inc/FormProcess.php but to the script where you define the variable
All you have to do is add input type hidden at the end of the form, so my correct form should look like this:
<form spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form ajax' name='contactOwner' action='' method='POST'>
<h4 id="responseOwner" class="success">
<!-- This will hold response from the server --></h4>
<fieldset>
<legend>Vaši podaci</legend>
<div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Vaše ime i prezime..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
<div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Vaš broj telefona..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->
<div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Vaš e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control -->
<div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Vaša poruka..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
</fieldset>
<input type="hidden" name="pages_id" value="<?=$pages_id?>">
<input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="POŠALJI"/>
</form>
I'm trying to submit an eMail via AJAX, but for some reason, nothing is working. I have counter and counter checked that the files (<script src="mail.js"></script>, jquery and url: "sendmail.php") are well mapped.
The page reloads, and nothing is submitted. I do not want any page reloads in the first place, the reason I am using AJAX.
What am I doing wrong? Thank you all in advance.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="mail.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<!-- Content -->
<div class="container">
<div class="row">
<div class="span12 subscribe">
<h3>Subscribe to our newsletter</h3>
<p>Sign up now to our newsletter and you'll be one of the first to know when the site is ready:</p>
<form class="form-inline" action="" method="post">
<input type="text" name="tasktitle" placeholder="Enter your email...">
<button type="submit" class="btn">Subscribe</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
</div>
</div>
</div>
</body>
</html>
mail.js
$(document).ready(function(){
$('.btn').click(function(e){
var current_time = 123;
var tasktitle = $("input#tasktitle").val();
var dataString = 'current_time='+ current_time + '&tasktitle=' + tasktitle;
$.ajax({
type: "POST",
url: "sendmail.php",
data: dataString,
success: function() {
$('.title').html("");
$('.success-message').html("✓ Logged!")
.hide()
.fadeIn(1500, function() {
$('success-message').append("");
});
}
});
return false;
});
});
sendmail.php
I have already created the directory ccts for the file to be written into.
<?php
$tasktitle = $_POST['tasktitle'];
setlocale(LC_TIME, "fi_FI");
date_default_timezone_set("Europe/Helsinki");
$date = strftime("%Y-%m-%d-%A");
$timesaved = strftime("%H:%M:%S");
$elapsedtime = $_POST['current_time'];
$file = "ccts/".$date.".txt";
$cont = 'time submitted: '.$timesaved.' - time elapsed: '.$elapsedtime.' - Email Address http://onvill.com/ : '.$tasktitle.''. "n";
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if($_POST) {
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'Contact.#site.com';
$subscriber_email = ($_POST['tasktitle']);
if(!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Insert a valid email address!';
echo json_encode($array);
}
else {
$f = fopen ($file, 'w');
fwrite($f, $cont);
fclose($f);
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thanks for your subscription!';
echo json_encode($array);
// Send email
$subject = 'New Subscriber!';
$body = "You have a new subscriber!\n\nEmail: " . $subscriber_email;
// uncomment this to set the From and Reply-To emails, then pass the $headers variable to the "mail" function below
//$headers = "From: ".$subscriber_email." <" . $subscriber_email . ">" . "\r\n" . "Reply-To: " . $subscriber_email;
mail($emailTo, $subject, $body);
}
}
?>
UPDATE
I get the error:
Uncaught ReferenceError: $ is not defined(anonymous function) # mail.js:1
HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="mail.js"></script>
</head>
<body>
<!-- Content -->
<div class="container">
<div class="row">
<div class="span12 subscribe">
<h3>Subscribe to our newsletter</h3>
<p>Sign up now to our newsletter and you'll be one of the first to know when the site is ready:</p>
<form class="form-inline" action="" method="post">
<input type="text" name="tasktitle" placeholder="Enter your email...">
<button type="submit" class="btn">Subscribe</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
</div>
</div>
</div>
</body>
</html>
in mail.js
$(document).ready(function(){
$('.btn').click(function(e){
var current_time = 123;
var tasktitle = $("input#tasktitle").val();
var dataString = 'current_time='+ current_time + '&tasktitle=' + tasktitle;
$.ajax({
type: "POST",
url: "sendmail.php",
data: $("form.form-inline").serialize(),
dataType:'json',
success: function(data) {
if(data.type=="success")
{
$('.title').html("");
$('.success-message').html("✓ Logged!")
.hide()
.fadeIn(1500, function() {
$('success-message').append("");
});
}
else
{
alert(data.message);
}
}
});
return false;
});
});
in PHP file
<?php
$response=array();
if(!empty($_POST))
{
$tasktitle = $_POST['tasktitle'];
setlocale(LC_TIME, "fi_FI");
date_default_timezone_set("Europe/Helsinki");
$date = strftime("%Y-%m-%d-%A");
$timesaved = strftime("%H:%M:%S");
$elapsedtime = $_POST['current_time'];
$file = "ccts/".$date.".txt";
$cont = 'time submitted: '.$timesaved.' - time elapsed: '.$elapsedtime.' - Email Address http://onvill.com/ : '.$tasktitle.''. "n";
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'Contact.#site.com';
$subscriber_email = ($_POST['tasktitle']);
if(!isEmail($subscriber_email)) {
$response['type'] = 'error';
$response['message'] = 'Insert a valid email address!';
}
else {
$f = fopen ($file, 'w');
fwrite($f, $cont);
fclose($f);
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thanks for your subscription!';
echo json_encode($array);
// Send email
$subject = 'New Subscriber!';
$body = "You have a new subscriber!\n\nEmail: " . $subscriber_email;
// uncomment this to set the From and Reply-To emails, then pass the $headers variable to the "mail" function below
//$headers = "From: ".$subscriber_email." <" . $subscriber_email . ">" . "\r\n" . "Reply-To: " . $subscriber_email;
mail($emailTo, $subject, $body);
$response['type'] = 'success';
$response['message'] = 'Mail sent successfully!';
}
}
else
{
$response['type'] = 'error';
$response['message'] = 'Invalid post request';
}
ob_clean();
echo json_encode($response);
just import jquery cdn before your mail.js
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="mail.js"></script>
jquery must be loaded before calling it.
This is because the sequence:
<script src="mail.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
your mail.js is on top and jquery after that. But in mail.js you are using $, and $ is not available there. Change the sequence and try again.
I am creating a mailing-list service.
I need to attach dynamically one or more files into an email, using php, phpmailer and only one "slot" for adding files in the html form.
I just know how to send one attachment, not two or more, in the same email.
here u are the html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div class="main_container">
<form action="phpmailer/sendmail.php" method="post" enctype="multipart/form-data" id="prenota">
<div class="form_title">
<h2>Mailing List</h2>
</div>
<div class="form_title">
<p>Message:</p>
</div>
<label for="message">
<textarea name="message"></textarea>
</label>
<label for="file">
Select one or more file to send
<input name="file" type="file" id="file_ok">
</label>
<div class="submit-container">
<input class="submit-button" type="submit" name="submit" value="Invia"><br>
</div>
</form>
</div>
</body>
</html>
and the php for the phpmailer (sendmail.php, it works with the hosting service I am usign):
<?php
require_once('libs/PHPMailer/PHPMailerAutoload.php');
$db= new PDO('mysql:host=00.000.000.000;dbname=dbname_1', 'dbname', 'dbpass');//connection setup
$m_list = $db->query("
SELECT id, nome, email
FROM mailing_list
")->fetchAll(PDO::FETCH_ASSOC);
$mail = new PHPMailer(true);
$mail->Port = 25;
$mail->CharSet = 'UTF-8';
//variables
$email_receiver = $m_list['email'];
$name_receiver = $m_list['nome'];
$nome_sender= "mr x";
$messagge= stripslashes($_POST['message']);
foreach ($m_list as $eachmail) {
$email_receiver = $eachmail['email'];
$name_receiver = $eachmail['nome'];
$mail->From = "service#email.it";
$mail->FromName = "service";
$mail->AddReplyTo($email_receiver, $name_receiver);
$mail->MsgHTML($body);
$mail->AddAddress($email_receiver, "dynamic name");
$mail->Subject = "Message from website";
$body = '<strong>email send to:</strong> ' . $name_receiver . '<br/>
<strong>email:</strong> ' . $email_receiver . '<br/>
<strong>message:</strong> ' . stripslashes($message) . '<br/><br/>';
$mail->MsgHTML($body);
$mail->Send(true);
$mail->ClearAllRecipients(true);
}
echo "mail sent";
?>
I imagine I need to store the files ito an array and then, for each files, create the relative attachment. Unfortunately I can't. Any help?
First of all I used an "injection" of Jquery, in order to add as much as inputs file I want in the dom of the main form, and to delete them if desired.
$( document ).ready(function() {
$( '#add_more' ).click(function() {
var current_count = $('input[type="file"]').length;
var next_count = current_count +1;
$('#prenota').prepend('<p id="here_' + next_count + '"><input type="file" name="file_' + next_count + '" /></p>')
$('#here_' + next_count + '').append('<a class="delete_this" href="#">delete</a>');
});
$('.delete_this').live('click', function(){
var current_todelete = $(this).closest("p").attr("id");
$('#' + current_todelete + '').remove();
});
});
Then I added some strings in the php file designated to collect post information and sendig emails, making it capable to carry attachments (as Synchro suggested me):
if (isset($_FILES)){
foreach ($_FILES as $file) {
$filename = $file['name'];
$filetype = $file['type'];
$filetmp_name = $file['tmp_name'];
$filesize = $file['size'];
if($filename){
$temPath = '../../../../../public/' . basename($filename);
//var_dump($temPath);
//die();
if (move_uploaded_file($filetmp_name, $temPath)) {
$mail->AddAttachment($temPath, $filename);
}
}
}
}else{
$mail->AddAttachment(false);
}
Hoping to be helpful to people with the same problem of mine.
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;
}
}
?>
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);
}
}
});