Attachments added through JavaScript function are not sent - php

I am using the following loop to send/attach multiple attachments to my email message.
foreach(array_keys($_FILES['attachment']['name']) as $key) {
$source = $_FILES['attachment']['tmp_name'][$key];
$filename = $_FILES['attachment']['name'][$key]; // original filename from the client
$mail->AddAttachment($source, $filename);
}
But only the first attachment i made is sended.
The form code is
<form method="POST" action="<?php $PHP_SELF ?>" enctype="multipart/form-data">
<input type="file" name="attachment[]" id="attachment" size="30"
onchange="document.getElementById('moreUploadsLink').style.display = 'block';" />
<div id="moreUploads"></div>
<div id="moreUploadsLink" style="display:none;">
Attach another File</div>
<input name="submit" type="submit" value="submit" />
</form>
When one click on Attach another file, another File Upload button is shown, through a JavaScript function:
<script type="text/javascript">
var upload_number = 1;
var attachmentlimit = 5;
function addFileInput() {
var d = document.createElement("div");
var file = document.createElement("input");
file.setAttribute("type", "file");
file.setAttribute("name", "attachment"+upload_number);
d.appendChild(file);
document.getElementById("moreUploads").appendChild(d);
upload_number++;
if(upload_number == attachmentlimit) {
document.getElementById('moreUploadsLink').style.display='none';
}
}
</script>
Only the file attached through the first FileUpload Button is attached and sended, not the others.
Help.

The problem is that you are setting the name attribute of your new input element to attachment1, attachment2, etc. You should be setting this name to attachment[], just like the original input you created.
If you still don't get all your attachments, you can try a var_dump($_FILES) in your PHP script to ensure that you are getting all the files the way you expect them.

Related

jquery: how to open an url in new tab with passing post data to that url

I have a php file localhost/~user/sample.php file which gets data from post method.
<?php
$you = $_POST["ids"];
$start= $_POST["start"];
echo $you."--".$start;
I want to write a jquery code which will open the url "localhost/~user/sample.php" in a separate window on button click inside my html page and also pass the arguments required for it.
I can use get method in php, but the number of variables are more
I would probably go for using a form, like so:
<form action="sample.php" method="post" target="_blank">
<input type="hidden" name="name1" />
<input type="hidden" name="name2" />
...
<input type="hidden" name="name20" />
<input type="submit" value="Go to page">
</form>
This is the most cross-browser JS-failsafe basic html version way of achieving this task that I can think of...
If you need to dynamically add form fields to the form, I believe you will find this question: Jquery - Create hidden form element on the fly handy. Copying the modified answer:
$('<input type="hidden" name="myfieldname" value="myvalue">').appendTo('form');
One way would be to dynamically create a hidden form and then submit it, make sure you encode the input:
var params = [['someKey0', 'someValue0'], ['someKey1', 'someValue1'], ['someKey2', 'someValue2'], ['someKey3', 'someValue3']];
var inputs = $.map(params,function(e,i){
return '<input type="hidden" name="'+e[0]+'" value="'+encodeURIComponent(e[1])+'"/>';
});
var form ='<form action="sample.php" id="hidden-form" method="post" target="_blank">'+inputs.join('')+'</form>';
$('#hidden-div').html(form);
$('#hidden-form').submit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hidden-div"></div>
Try this....
<form id="myForm" action="sample.php" method="post">
<?php
echo '<input type="hidden" name="'.htmlentities($you).'" value="'.htmlentities($start).'">';
?>
</form>
<script type="text/javascript">
document.getElementById('myForm').submit();
</script>
if you send request with javascript to any php page; it sends a request and gets the respose to the page which has sent request and you continue process your data at your first page. So if you want to open your sample.php and also send your post data within; you must send your data with something like php form.
Submitting forms: http://www.w3schools.com/php/php_forms.asp
If you want to use js post, you can do something like below:
teams.php:
data = { teams : ['Real Madrid','Barcelona','etc']};
var response = null;
$.ajax({
url : 'mypostfile.php',
type : 'POST',
data : data
})
.done(function(resp){ response = resp; //it returned from php echo })
.fail(function(){ console.log('fail'); //post process failed. });
mypostfile.php:
if(isset($_POST['teams'])){
$teams = $_POST['teams'];
echo $teams[0]; //response : Real Madrid
}
Hope it helps.

Dynamically adding input file object with form

I designed a form in form.php with a file input. When I press +input button, a new file input object should be generated and save them to my mysql server.
My code here,
form.php
<div id="enterReplyReferenceList">
<div class="enterReplyRefInputContainer">
<div class="enterReplyRefInput">
<form action="submit.php" method="POST" enctype="multipart/form-data">
<input type="hidden" value="<?php echo $userID; ?>" name="userID">
<input type="submit" value="SEND"/>
<input type="file" name="enterRefFile[]" multiple class="enterRefFile" accept="application/pdf,image/jpeg, image/png, image/jpg"/>
</form>
</div>
</div>
</div>
<button onclick="appendRef()">+input</button>
form.js
function appendRef(){
var inputclass = document.getElementsByClassName('enterReplyRefInputContainer')[0];
var inputclassChild = document.createElement('div');
inputclassChild.innerHTML = inputclass.innerHTML;
var newClass = document.getElementById("enterReplyReferenceList").appendChild(inputclassChild);
newClass.className = "enterReplyRefInputContainer";
submit.php
for($i=0; $i<count($_FILES['enterRefFile']['name']); $i++) {
$tmpFilePath = $_FILES['enterRefFile']['tmp_name'][$i];
if ($tmpFilePath != ""){
$fileData = addslashes(file_get_contents($_FILES['enterRefFile']['tmp_name'][$i]));
$fileName = addslashes($_FILES['enterRefFile']['name'][$i]);
$fileType = $_FILES['enterRefFile']['type'][$i];
if($fileData != null){
if($fileType == "application/pdf" || $fileType == "image/png" || $fileType == "image/jpeg" || $fileType == "image/jpg"){
mysql_query("INSERT INTO attachment (attachData, dataType, attachName, userID) VALUES('$fileData','$fileType','$fileName', '$userID')");
}
}
}
}
When I pressed the +input button, a new input file object is generated with the same look with the original and I can select the files. However, only a single file can be uploaded to my mysql db after I clicked the submit button. Can somebody tell me why the new file input cannot be uploaded? Is the new objects will not be sent?
The problem is that your input button is cloning your whole div, which has the form, so when you click "Submit" you're uploading one form with one file element. Here's an updated version (all in one file, you can separate to your liking):
<button onclick="appendRef()">+input</button><br><hr>
<form action="submit.php" method="POST" enctype="multipart/form-data">
<input type="hidden" value="<?php echo $userID; ?>" name="userID">
<div id="enterReplyReferenceList">
<div class="enterReplyRefInputContainer">
<div class="enterReplyRefInput">
<input type="file" name="enterRefFile[]" multiple class="enterRefFile" accept="application/pdf,image/jpeg, image/png, image/jpg"/>
</div>
</div>
</div>
<hr>
<input type="submit" value="SEND"/>
</form>
<script>
function appendRef(){
var inputclass = document.getElementsByClassName('enterReplyRefInputContainer')[0];
var inputclassChild = document.createElement('div');
inputclassChild.innerHTML = inputclass.innerHTML;
var newClass = document.getElementById("enterReplyReferenceList").appendChild(inputclassChild);
newClass.className = "enterReplyRefInputContainer";
}
</script>
Button click is outside of the form so you don't do a submit action on it (unless you want to use a blocking action like jQuery preventDefault(), and you only need one submit for the whole form.

multiple image upload using php mysql javascript

hi i want to upload multiple images and insert into mysql db using a single form with php, mysql and javascript. i'm applying coding. php upload will works fine. but javascript code for multiple select not working. i'm setting + and _ symbol for add or delete multiple select boxes for selection and upload in a single submit. the upload and insert db works fine.but the incement(+) symbol not working. i'm able to upload only one image at a time. i'm displayed the code below. please help me.
index.php:
<html>
<head>
<title>Multiple Upload</title>
</head>
<script language="javascript">
function fncCreateElement(){
var mySpan = document.getElementById('mySpan');
var myLine = document.getElementById('hdnLine');
myLine.value++;
// Create input text
var myElement1 = document.createElement('input');
myElement1.setAttribute('type',"text");
myElement1.setAttribute('name',"txtGalleryName"+myLine.value);
myElement1.setAttribute('id',"txt"+myLine.value);
mySpan.appendChild(myElement1);
// Create input file
var myElement2 = document.createElement('input');
myElement2.setAttribute('type',"file");
myElement2.setAttribute('name',"fileUpload"+myLine.value);
myElement2.setAttribute('id',"fil"+myLine.value);
mySpan.appendChild(myElement2);
// Create <br>
var myElement3 = document.createElement('<br>');
myElement3.setAttribute('id',"br"+myLine.value);
mySpan.appendChild(myElement3);
}
function fncDeleteElement(){
var mySpan = document.getElementById('mySpan');
var myLine = document.getElementById('hdnLine');
if(myLine.value > 1 )
{
// Remove input text
var deleteFile = document.getElementById("txt"+myLine.value);
mySpan.removeChild(deleteFile);
// Remove input file
var deleteFile = document.getElementById("fil"+myLine.value);
mySpan.removeChild(deleteFile);
// Remove <br>
var deleteBr = document.getElementById("br"+myLine.value);
mySpan.removeChild(deleteBr);
myLine.value--;
}
}
</script>
<body>
<form action="upload.php" method="post" name="form1" enctype="multipart/form-data">
<input type="text" name="txtGalleryName1"><input type="file" name="fileUpload1">
<input name="btnCreate" type="button" value="+" onClick="JavaScript:fncCreateElement();">
<input name="btnDelete" type="button" value="-" onClick="JavaScript:fncDeleteElement();"><br>
<span id="mySpan"></span>
<input name="hdnLine" type="hidden" value="1">
<input name="btnSubmit" type="submit" value="Submit">
</form>
</body>
</html>
upload.php:
<?php
include("config.php");
for($i=1;$i<=(int)($_POST["hdnLine"]);$i++)
{
if($_FILES["fileUpload".$i]["name"] != "")
{
if(copy($_FILES["fileUpload".$i]["tmp_name"],"shotdev/".$_FILES["fileUpload".$i]["name"]))
{
$strSQL = "INSERT INTO gallery ";
$strSQL .="(GalleryName,Picture) VALUES ('".$_POST["txtGalleryName".$i]."','".$_FILES["fileUpload".$i]["name"]."')";
mysql_query($strSQL);
echo "Copy/Upload ".$_FILES["fileUpload".$i]["name"]." completed.<br>";
}
}
}
echo "<br><a href='view.php'>View file</a>";
mysql_close();
?>
Change this line:
<input name="hdnLine" type="hidden" value="1">
into:
<input id="hdnLine" type="hidden" value=1>

I want to single ajax uploader script into multiple uploader with the help of Iframe Javascript PHP

I am using this reference
http://www.openjs.com/articles/ajax/ajax_file_upload/response_data.php
for ajax uploader ,its working absolutely fine for single upload but i want to convert this script into multiple upload with the help of your guidance also helps are definitely appreciated..
I just want to know how do i target a multiple iframe with the using of single form. Current script is target on a spacefic formId like this and this form contain only one input file...
Code
<script type="text/javascript">
function init() {
document.getElementById("file_upload_form").onsubmit=function() {
document.getElementById("file_upload_form").target = "upload_target";
document.getElementById("upload_target").onload = uploadDone;
}
}
window.onload=init;
<script>
<form id="file_upload_form" method="post" enctype="multipart/form-data" action="http://www.appifylabs.com/web/php-upload-progress-bar/uploaderSecond/upload.php/">
<input name="file" id="file" size="27" type="file" multiple="multiple"/><br />
<input type="submit" name="action" value="Upload Image" /><br />
<iframe id="upload_target" onload="uploadDone()" name="upload_target" src="" style="width:600px;height:600px;border:1px solid #ccc;"></iframe>
</form>
Attempt didn't work
<script type="text/javascript">
function init() {
document.getElementById("file_upload_form").onsubmit=function() {
document.getElementById("file_1").target = "upload_target_1";
document.getElementById("file_2").target = "upload_target_2";
}
}
window.onload=init;
<script>
Notice
I don't want to use any third party uploader like uploadify,JqueryUploader,Valum etc only the reason for learn
Each form can have only one target. And target is a property of the FORM element, not the INPUT ones (you tried above).
One possible solution is to clone the form using Jquery, set the corresponding target to the required IFRAME and submit each clone.

check filename before posting using jquery/ php

I need jquery to check if my posted filename (up_image) is empty or not.
if it's empty i need a div tag to be shown and come with some kind of alert message.
if not, just do the
$("#submit").submit();
<form action="/profile/" method="post" enctype="multipart/form-data" id="submit">
<p>
<label for="up_image">image:</label>
<input type="file" name="up_image" id="up_image" />
</p>
Upload
</form>
$(function() {
$("#post_submit").click(function() {
var fil = $("#up_image");
if($.trim(fil.val()).length == 0) {
alert("Choose a file!");
fil.focus();
return false;
}
$("#submit").submit();
});
});
1: use a standard submit button to submit your form rather than a javascript-dependent link, for accessibility reasons, and to prevent brokenness if someone tries to right-click-open-in-new-window or other similar action on the link. If you want it to look like a link, you can still use a button, just apply some CSS to make it no longer look like a button.
2: use the form.onsubmit event to do validation rather than relying on a submit button click (forms can also be submitted by pressing enter, which may not always generate a button click)
<form id="uploadform" method="post" action="/profile/" enctype="multipart/form-data">
<p>
<label for="up_image">image:</label>
<input id="up_image" type="file" name="up_image" />
</p>
<p>
<input type="submit" value="Upload" />
</p>
</form>
<script type="text/javascript">
$('#uploadform').submit(function(e) {
if ($('#up_image').val()=='') {
alert('Please choose a file to upload.');
e.preventDefault();
}
});
</script>

Categories