HTML file input with possibility to input several files one after another - javascript

I'm looking for a possibility to input several files in a row in an HTML form. It strikes me that there seems to be no easy solution for this (or at least I haven't been able to find it despite several hours of searching). If I use the multiple attribute in an <input type="file" name="myFiles[]" multiple />, I can choose several files at a time holding Ctrl, but if I choose one file at first, then click the input field again and choose another one, the second file seems to overwrite the first one.
So I thought I might try to use javascript to add more <input type="file" name="myFiles[]" /> fields (with the same name), since I have seen something similar somewhere. I tried the following:
JavaScript:
function addInputFileEle() {
var field = document.getElementById("filesField");
var row = '<input type="file" name="myFiles[]" onchange="addInputFileEle();" />';
field.innerHTML += row; // add one more <input type="file" .../> element
}
HTML:
<form method="post" action="#" enctype="multipart/form-data">
<fieldset id="filesField"> <!--for adding more file-input rows-->
<input type="file" multiple name="myFiles[]" class="multi" onchange="addInputFileEle();" />
</fieldset>
<input type="submit"/>
</form>
The document indeed does create additional file-input elements whenever I click on one of them and select a file, BUT: The file does not get uploaded! I mean, after I select the file, the file name does not get displayed, instead, it still says "Choose a file" (or "Select a file", not sure about English). So apparently my onchange="addInputFileEle()" overwrites the normal reaction (the file getting 'loaded' into the input element)? Even though this does not seem logical to me. Can anyone help? Why does the file not get selected in the end? Or maybe there is a simpler solution than mine, which would of course be very welcome. Thanks in advance!

Ok I will just post my solution in case anyone else is searching for a way to select several files for upload one by one. As #CodingWithClass pointed out, I was resetting the input field by using something like parentElement.innerHTML += additionalInputElement;. Instead, I should have used appendChild as #JoshuaK suggested:
<html>
<head>
<meta charset="UTF-8">
<script>
function addFileInput(fieldsetName, firstInputId) {
var fs = document.getElementById(fieldsetName);
// only add one if the last file-input field is not empty
if(fs.lastElementChild.value != '') {
var firstInputFile = document.getElementById(firstInputId);
var newInputFile = document.createElement("input");
newInputFile.type = firstInputFile.type;
newInputFile.name=firstInputFile.name;
newInputFile.multiple=firstInputFile.multiple;
newInputFile.class = firstInputFile.class;
newInputFile.onchange=firstInputFile.onchange;
fs.appendChild(newInputFile);
}
}
</script>
<title>MultiFile-Testing</title>
</head>
<body>
<?php print_r($_FILES); // see if files were uploaded in the previous round ?>
<form method="post" action="#" enctype="multipart/form-data">
<fieldset id="filesFS">
<input type="file" multiple name="myFiles[] id="firstInputFile" onchange="addFileInput('filesFS', 'firstInputFile');" />
</fieldset>
<input type="submit"/>
</form>
</body>
</html>

Related

How to write input value to a file in PHP?

i am quite a beginner in PHP and i wanted to create a input: If you click a button, Javascript will submit it and add linebreak (\n) at the end of what you wrote in the input box, and PHP will write the final result into a file called result.txt. However, when checking result.txt, there is nothing written at all.
HTML
<input id="test" type="text">
<form id="formie" action="test.php" method="post">
<input id="testz" type="text" name="really" hidden="hidden" disabled="disabled"><br>
<button onclick="trigger1()">Submit</button>
</form>
<!-- 2 input boxes, the hidden one is meant to be set to have the final result and with it i do the request -->
<script>
var int;
function trigger1() {
int = document.getElementById('test').value;
document.getElementById('testz').value = int + "\n";
document.getElementById('formie').submit();
}
</script>
PHP
<?php
$postreq = $_POST["really"];
$finaldata = $postreq;
file_put_contents("result.txt", $finaldata, FILE_APPEND);
header("Location: https://domain.tld/test.html");
exit;
?>
No error when stopping the redirect (domain.tld/test.html) and no error in server logs. Why is this happening? I even tried to check this with jshint.com and phpcodechecker.com and both told me no errors
Credit to #user3783243: The problem lies here:
<input id="testz" type="text" name="really" hidden="hidden" disabled="disabled">
Disabled elements cannot have values
Working code:
<input id="testz" type="text" name="really" hidden="hidden">
To answer the question, elements with the disabled attribute are not submitted or you can say their values are not posted
Try removing the "disabled" attribute from your hidden input.
Refer to: Disabled form inputs do not appear in the request, which has reference to the w3 specs explaining that as well.

How do I refer to a specific HTML <form> or web page from within a .js file?

I have a .js file with setCookie() and getCookie() functions which are working fine. I'm running into a problem when trying to use this same .js file with 2 different web pages. For example, one page's cookie sets name, room number, and beverage selection, while the other page's cookie sets name, address line 1, address line 2, etc...
Thus, I will need to account for differences in the 2 page's forms in the .js file. I thought that I could reference the particular form I'm addressing by its form name (they have different form names) but that isn't working:
if (document.getElementsByTagName("form") == document.getElementsByName("form1"))
{
document.cookie = 'Name = ' + userName; 'expires = ' + userExpires;
document.cookie = 'Room = ' + userPrt1; 'expires = ' + userExpires;
document.cookie = 'Drink = ' + userPrt2; 'expires = ' + userExpires;
}
Thus, my question is, when I have to add an if statement to handle code specific to one particular form (or one particular web page), how do I do this?
Thank you
EDIT: I'm not really sure this will be helpful, but since it was requested, here is the HTML:
<!doctype html>
<html lang="en">
<head>
<title>Javascript</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="mycss.css"/>
<script type="text/javascript" src="myjs.js"></script>
</head>
<body onLoad="javascript:getCookie();">
<header>
<img src="js.png" width="800" height="135"/>
</header>
<main>
<h2>JavaScript Cookie Test</h2>
<br><br>
<form name="form1" id="form1id" action="javascript:setCookie();">
Name: <input type="text" name="customer" id="customer" required /><br><br>
Room: <input type="text" name="roomNumber" id="roomNumber" required /><br><br><br>
What type of coffee would you like to order?<br><br> <!-- It seems radio input would be better here -->
<input type="checkbox" name="cbox" value="regular" />Regular<br>
<input type="checkbox" name="cbox" value="espresso" />Espresso<br>
<input type="checkbox" name="cbox" value="cappuccino" />Cappuccino<br>
<input type="checkbox" name="cbox" value="mocha" />Mocha<br>
<input type="checkbox" name="cbox" value="raspberry" />Raspberry<br><br>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</main>
As I mentioned, everything works fine in terms of setting and getting the cookie, whether my JavaScript is in the HTML file or in a separate .js file. It's only when I try to add code in the .js file that references a specific form (or web page) that I do not succeed.
Should I be referencing the web page instead of the form? If so, how would I do this in an if statement? Thank you!
EDIT: I want to add a brief clarification in case it will be helpful. What I want to know is how to reference the form or web page calling a function in the .js file. If form1 or index1.html called the setCookie() function, I want to add an if code block. If form2 or index2.html called the setCookie() function, I want to add a different if code block. Thank you.
Have you tried giving each form an id and using getElementById() instead ? I think your error is coming from the fact that getElementsByTagName returns an array so you're trying to compare an array of elements to a single element
I'm not sure to understand your question, but in case I have you could just check if the form exists, by its id.
if (document.getElementById('form1') !== null)
{
// there is a form1
}
else if (document.getElementById('form2') !== null)
{
// there is a form2
}
for the first, getElementsByName() doesn't return single node, but a node collection, so if you want to access the first matching node, you have to use
document.getElementsByName("form1")[0]
For the second, you can simply use document.forms property where you have access to all forms on your page.
EDIT:
In document.forms you can access to form by index of its occurrence (document.forms[1] returns the second form on page) or you can use name attribute value (document.forms["form1"] returns form with name "form1").
Okay, I finally figured out an answer to this.
HTML:
<script type="text/javascript">var formName = "form1"</script>
<form name="form1" action="javascript:setCookie(formName);">
insert form code...
</form>
Then, in the .js file:
function setCookie(formName)
{
insert cookie code...
}
And the form name is passed to the JavaScript page, so I can use it to add cookie code that is specific to form1.
I was hoping to find a way to know which form called the JavaScript page, but I'm starting to think that's not possible, since the question has been posted for 5 days without a resolution. Fortunately, this resolves the issue just as easily as knowing which form called the JavaScript page.
I appreciate everyone's input.

Submit button with POST instead of using HTML form

I have a form inside a form and this makes the top form unresponsive. When I take off the second form (which is inside the first form), the first form works. This is the second form I have:
<form action="imgupload.php" method="post" enctype="multipart/form-data">
<h3>Upload a new image:</h3>
<input type="file" name="fileToUpload" id="fileToUpload">
<br>
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid">
<input type="hidden" value="User" name="user">
<input type="submit" value="Upload Image" name="imgup">
</form>
Since this makes the first form not work, I was wondering if I can take off the form fields and then the submit button can send the form data to the imgupload.php like this.
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid">
<input type="hidden" value="User" name="user">
<input type="submit" value="Upload Image" name="imgup" action="imgupload.php" method="post" enctype="multipart/form-data">
This does not work now. Is there a way I can get this working? If not, what's an alternative way to send this data to the other php?
Since you are uploading files, have a look at Ravi Kusuma's Hayageek jQuery File Upload plugin. It's simple, it's a Swiss Army Knife, and it works.
Study the examples.
http://hayageek.com/docs/jquery-upload-file.php
Ravi breaks down the process into three simple steps, that basically look like this:
<head>
<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet"> // (1)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script> // (1)
</head>
<body>
<div id="fileuploader">Upload</div> // (2)
<script>
$(document).ready(function(){
$("#fileuploader").uploadFile({ // (3)
url:"my_php_processor.php",
fileName:"myfile"
});
});
</script>
</body>
The final step is to have the PHP file specified in the jQuery code (in this case my_php_processor.php) to receive and process the file:
my_php_processor.php:
<?php
$output_dir = "uploads/";
$theFile = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
Note the relationship between myfile in the PHP ($_FILES["myfile"]), and the filename specified in the jQuery code block.
Don't forget to check out the server-side code from the Server Side tab -- you need both parts (js and php).
Looking at your question again, you will probably want to use this functionality as well:
dynamicFormData: function()
{
var data ={ location:"INDIA"}
return data;
}
or
dynamicFormData: function(){
return {
newID: $("#newNID").val(),
newSubj: $("#newSubj").val(),
newBody: $("#newBody").val(),
formRole: $('#formRole').val()
};
These will appear on the PHP side, thus:
$newID = $_POST['newID'];
$subj = $_POST['newSubj'];
etc
As with any plugin, resist the temptation to just plop it into your code. Do a couple of quick-and-dirty tests with it first. Kick its tires. Fifteen minutes will save you two hours.
And don't forget to verify what was uploaded. You never know when a developing country black hat might be trying to get a new account.

Variable Transfer: Web Form that connects with PHP to Database

Hello and thank you for viewing my question. I am a complete beginner and am looking for simple ways to do the following...
What I have in seperate linked documents:
HTML, CSS, Javascript, PHP
What I am having trouble with:
I need to use something like JSON (although I would also accept XML requests or Ajax at this point if they work) to transfer variables from Javascript to PHP. I need the variables to search in a database, so they need to be literally available within PHP (not only seen on a pop-up message or something).
I have seen a LOT of different ways to do this, I have even watched tutorials on YouTube, but nothing has worked for me yet. The things I am having the biggest problem with is that when I add a submit button to my form it doesn't submit my form and I don't know why.
Form code snippet:
<form id="form" name="input" method="post" action="javascript:proofLength();">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit" onsubmit="post();">
</form>
The second to last line there doesn't work. Do I need javascript to submit the form? Because I really thought that in this case it was part of the functionality of the form just like method="post"...
The other thing is that for JSON, I have no idea what to do because my variables are determined by user input. Therefore, I cannot define them myself. They are only defined by document.getElement... and that doesn't fit the syntax of JSON.
Those are really my main problems at the moment. So if anyone could show me a simple way to get this variable transfer done, that would be amazing.
After this I will need to search/compare in my database with some php/sql (it's already connecting fine), and I need to be able to return information back to a in HTML based on what I find to be true. I saw one example, but I am not sure that was very applicable to what I am doing, so if you are able to explain how to do that, that would be great also.
Thank you very, very much.
April
You don't need ajax to submit this form. You don't even need javscript. Just do this:
<form id="form" name="input" method="post" action="mytarget.php">
<input id="userinput" name="userinput" type="text" autofocus />
<input id="submit" type="submit" value="submit" />
</form>
This will send the form data to mytarget.php (can be changed of course)
See that i have added the name attribute to your text-field in the form and i changed the type of the button to submit.
Now you can work the Data in mytarget.php like this:
<?
$username = $_POST['userinput'];
echo "Your name is: ".$username;
?>
You wanted to have a check for length in the submit. There are two ways to this:
Before the input is send (the server is not bothered)
Let the server Check the input
for 1 you will have to append a event listener, like this:
var form = document.getElementById("form");
form.addEventListener("submit", function(event){
console.log("test");
var name = form.elements['userinput'].value;
if(name.length < 3){
alert("boy your name is short!");
event.preventDefault();
}
});
Enter a name with less then 3 characters and the form will not be submitted. test here: http://jsfiddle.net/NicoO/c47cr/
Test it Serverside
In your mytarget.php:
<?
$username = $_POST['userinput'];
if(strlen($username) > 3)
echo "Your name is: ".$username;
else
echo "your name was too short!";
?>
You may also do all this with ajax. You will find a lot of good content here. But I'd recommend a framework like jQuery to do so.
The problem is in this line
<form id="form" name="input" method="post" action="javascript:proofLength();">
The action should be a PHP page (or any other type of server script) that will process the form.
Or the proofLength function must call submit() on the form
In the php page you can obtain variable values using $_GET["name"] or $_POST["name"]
To summarize; your code should look like this
<form id="form" name="input" method="post" action="yourpage.php">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit">
</form>
and for your php page:
<?php
$userinput = $_POST["userinput"];
//Do what ever you need here
?>
If you want to do something in your javascript before submitting the form, refer to this answer

Get files from input.files instead of value on submit

I have following problem. I have input field in form, type of file:
<FORM action="http://server.com/cgi/handle"
enctype="multipart/form-data"
method="post">
<P>
What is your name? <INPUT type="text" name="submit-name"><BR>
What files are you sending? <INPUT type="file" name="files"><BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</FORM>
I am setting using JavaScript also files property of this input and I want this input on submit of form send the file property instead of his value. Is it possible to do so?
var data = e.dataTransfer;
var input = dojo.byId(inputName);
var file = data.files[i];
input.files[0] = file;
data is a datatransfer object, I am getting files from there.
I know, it will be possible only in few browsers, I dont care. I just need to get it working at least in FF.
So if I understand you correctly you drop some files and you want to populate a file input object
I see a drop example here http://help.dottoro.com/ljslrhdh.php
but to populate the file field you will need a pretty heavy privilege change using a signed script - UniversalFileRead is probably the one you need

Categories

Resources