Phpmailer: multiple dynamic attachments in one form - php

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.

Related

PhpMailer: could not access file error, while sending upload file from tmp directory as attachment

I am trying to send the file which is uploaded and gets saved to tmp directory as an attachment. I am using PhPMailer but i am getting Could not access file error. The mail is getting sent with text in it on clicking submit but file which gets uploaded is not getting sent. I have gone through similar type of asked questions but none could solve the issue.
Here is the code.
<?php
if(isset($_POST['submit'])){
include('PHPMailer_5.2.0/class.phpmailer.php');
$content = 'Hello world!';
$email = new PHPMailer();
$email->From = 'info#example.com';
$email->FromName = 'Your Name';
$email->Subject = 'Subject';
$email->Body = $content;
$email->AddAddress( 'xxx#gmail.com' );
$email->AddAttachment( $_FILES['fileUpload']['tmp_name'], $_FILES['fileUpload']['name'] );
return $email->Send();
}
?>
<html>
<head>
<body>
<form id="sunrise" name="sunrise" method="post" action="">
<div class="form-group uploader col-xs-4">
<label class="coole" id="no-print">Upload Child's Image:</label>
<input name="fileUpload" type="file" id="fileUpload" class="no-print" required />
<br />
<div name="image-holder" id="image-holder"> </div>
</div>
<div class="col-xs-4">
<input type="text" name="student_name" class="form-control" id="add_student_first_name" placeholder='Your Name' required>
</div>
<button type="submit" class="btn btn-default" id="no-print" name="submit" value="submit">Submit</button>
</form>
<script>
$("#fileUpload").on('change', function() {
if (typeof(FileReader) != "undefined") {
var image_holder = $("#image-holder");
image_holder.empty();
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image",
"width": "113px",
"height": "151px"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("This browser does not support FileReader.");
}
});
</script>
<script type="text/javascript">
document.getElementById('date').valueAsDate = new Date();
</script>
</body>
</html>

Get value from another file PHP

I'm using PHPMailer inside WordPress for sending mails. For this I have 3 files:
contacts.php - file with html form:
<?php
/*
* Template Name: Contacts
*/
get_header(); ?>
<div class="container page">
<h2>Напиши нам</h2>
<div class="row">
<div class="col-lg-5">
<form action="<?php bloginfo('template_url');?>/mailer.php" method="post">
<label for="fname">Имя*</label>
<input type="text" class="form-control" id="fname" name="first-name" required>
<label for="tel">Телефон*</label>
<input type="tel" class="form-control" id="tel" required name="phone">
<label for="tel">E-mail</label>
<input type="tel" class="form-control" id="email" name="email">
<label for="">Сообщение*</label>
<textarea required class="form-control" rows="8" name="msg"></textarea>
<button type="submit" class="btn btn-success" id="btn-contacts">Отправить</button>
</form>
</div>
<div class="col-lg-7">
</div>
</div>
</div>
<?php get_footer(); ?>
mailer.php - the handler for the form:
<?php
$fname = $_POST["first-name"];
$phone = $_POST["phone"];
$email = $_POST["mail"];
$msg = $_POST["msg"];
require_once("lib/phpmailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->FromName = "SomeName";
$mail->Host = "smtp.yandex.ru";
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->CharSet = 'UTF-8';
$mail->SMTPAuth = true;
$mail->Username = "username";
$mail->Password = "password";
$mail->AddAddress("someaddress#yandex.ru", "Name");
$mail->WordWrap = 50;
$mail->SetFrom("someaddress#ya.ru", "OwnerName");
$mail->IsHTML(true);
$mail->Subject = $fname;
$body = file_get_contents("test.php");
$mail->MsgHTML($body);
if($mail->Send())
echo "Everything is okay";
else
echo "Error!";
?>
test.php - html markup for letter:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h5>First Name of Person:</h5>
<?php
echo $fname; //how can I get this variable value???
?>
</body>
</html>
And I have faced with a problem.
How can I get this? (see the third snippet and a comment inside). Thank you in advance!
You can store it in session on your POST request and then display it. Also, in WP sessions are not enabled by default. You need to enable them like so.
if (!session_id()) {
session_start();
}
$_SESSION['firstName'] = $_POST['first-name']; // Store
<?php echo $_SESSION['firstName']; // Display ?>
Suggest using herdoc syntax because file_get_contents does not automatically translate VARS unless you run eval() on it(I think). So, simply include('test.php'); which contains...
$body = <<<EOD
....
<h5>First Name of Person:</h5>
$fname
....
EOD;
You can do Heredoc syntax to define the html text along with variables. file_get_contents just read the text source of the file and store in your variable. You have to include this file wherever it needed and use heredoc syntax :
$body = <<<HTML
<h5>First Name of Person:</h5>
{$fname}
HTML;
Of you can define your test.php with some template tags . Use some template variables and replace the value with the actual variable in your form processing code .
In test.php, use
<h5>First Name of Person:</h5>
{first_name}
Then after getting the contents using file_get_contents, replace template variables with the value received from POST .
$body = file_get_contents("test.php");
$body = str_replace("{first_name}",$fname,$body);
Do this for all values to be replaced .

Submision via AJAX call not working

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.

PHP mail form problems?

sorry if this seems like a silly question but I'm really stuck.
I'm using a form with php to allow users to send mail from my website and everything works fine except when you want to add more than one 'item', 'amount' and 'boxeach' to the form.
The script I use does duplicate the items but keeps them with the same name, which means that my php will only read and send one of them in the email. Is there any way to change that so all of those three elements are put in the email, with one appearing under the other?
This is the script I use to duplicate (used with a button):
<script>$(function() {
$('#copy').click(function(){
var content = $('#content').html();
var newdiv = $("<div>");
newdiv.html(content);
$('#content').after(newdiv);
});
});</script>
Here is my full html code:
<head>
<title>WHOLESALE ORDER</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>$(function() {
$('#copy').click(function(){
var content = $('#content').html();
var newdiv = $("<div>");
newdiv.html(content);
$('#content').after(newdiv);
});
});</script>
label,a
{
font-family : Arial, Helvetica, sans-serif;
font-size : 12px;
}
</style>
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>
</head>
<body>
<h2>WHOLESALE ORDER <strong><script type="text/javascript">
var date = new Date();
var month = new Array(7);
month[0] = "01";
month[1] = "02";
month[2] = "03";
month[3] = "04";
month[4] = "05";
month[5] = "06";
month[6] = "07";
month[7] = "08";
month[8] = "09";
month[9] = "10";
month[10] = "11";
month[11] = "12";
var year = date.getYear();
if (year < 2000) { year+=1900; }
document.write(date.getDate() + "/" + month[date.getMonth()] + "/" + year);
</script></strong></h2>
<form method="POST" name="contactform" action="contact-form-handler.php">
<p>
<table><tr><td>
<label for='name'>Name:</label> <br>
<input type="text" name="name">
</td>
<td>
<label for='email'>Email:</label> <br>
<input type="text" name="email">
</td></tr></table>
</p>
<p>
<table><tr><td>
<label for='address'>Delivery Address:</label> <br>
<input type="text" name="address">
</td>
<td>
<label for='telephone'>Telephone:</label> <br>
<input type="tel" name="telephone">
</td></tr></table>
</p>
<p>
<div id="content"><table><tr><td><label for='amount'><input type="text" name="amount"></label>
<label for='items'><select name="items">
<option value="APPLE BAG">APPLE BAG</option>
<option value="APPLE BRAMLEY">APPLE BRAMLEY</option></select></label>
<label for='boxeach'><select name="boxeach">
<option value="BOX">BOX</option>
<option value="EACH">EACH</option>
</select></label>
</td></tr></table></div>
</p>
<p>
<input type="button" id="copy" value="Add another item +"/>
</p>
<input type="submit" value="Submit"><br>
</form>
<script language="JavaScript">
var frmvalidator = new Validator("contactform");
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email","Please enter a valid email address");
</script>
Here is my full php code:
<?php
$errors = '';
$myemail = 'someone#gmail.com';//
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['items']) ||
empty($_POST['boxeach']) ||
empty($_POST['amount']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$amount = $_POST['amount'];
$items = $_POST['items'];
$boxeach = $_POST['boxeach'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "WHOLESALE ORDER $name";
$email_body = "You have received a new message. ".
" Here are the details:\n $name \n $email_address \n \n \n $amount $items $boxeach";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>
When you click $("#copy) you create a div with information,that rewrites the privous one.
What you can do is to make a hidden input which will be outside of the #content div since you are rewriting it's html.
<input type="hidden" name="name_string">
And on click when you create a div also append the information to your hidden input:
$('#copy').click(function(){
var hidden = $("input[name='name_string']);
hidden.val(hidden.val() +","+ $("input[name='name']).val());
var content = $('#content').html();
var newdiv = $("<div>");
newdiv.html(content);
$('#content').after(newdiv);
});
Then in php you will get $_POST["name_string"] which will be like "name1,name2,name3,". You can use explode function in php to create and array from this string:
$array = explode(",", $_POST["name_string"]);
The problem you're having is that you're not making an array of the elements to store multiple values. Your script is just recreating a div. So the simple solution is that add "[]" to your amount, itmes and boxeach elements. i.e
<input type="text" name="amount[]" />
<select name="items[]">...</select>
<select name="boxeach[]">...</select>
Than in your php code change these lines from
$amount = $_POST['amount'];
$items = $_POST['items'];
$boxeach = $_POST['boxeach'];
to
$amount = implode(',',$_POST['amount']);
$items = implode(',',$_POST['items']);
$boxeach = implode(',',$_POST['boxeach']);
or manipulate the posted array in what ever way you like.
I hope my it helps you.

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