I have a form that is dynamically created using document.createElement. Components are created in the same way. The form is used to upload a file to a PHP script and, when submitted, loads the response in an iframe specified by the target attribute of the form.
Unfortunately, the server receives an empty $ _FILES array, and when I check the POST request, I see that the file data was not included in the request. If I’m on the fly instead, use the Google Chrome developer tools to edit the dynamically created form (in this process I just EDIT and then absolutely do not change any of the code), the presentation form works fine after that, sending the corresponding file data.
So, this makes me realize that there is nothing wrong with building my form in html, because it worked without changing anything. What makes me think that the browser doesn’t like me to dynamically create file input elements?
For completeness, here is a dynamically generated form:
<form method="POST" action="includes/uploadPic.php" enctype="multipart/form-data" target="fileResponse"> <input type="file" name="pic"> <input type="submit" value="Upload"> </form>
And print_r($_FILES) gives an empty server on the server.
Can someone explain this to me? My alternative is to statically create a hidden form in the document and just add it to the corresponding div when I need it, but I really don't like it.
Below is the code that generates the form:
var form = document.createElement("form"); var fileUpload = document.createElement("input"); var uploadBut = document.createElement("input"); form.setAttribute("method", "POST"); form.setAttribute("action", "includes/uploadPic.php"); form.setAttribute("enctype", "multipart/form-data"); form.setAttribute("target", "fileResponse"); fileUpload.setAttribute("type", "file"); fileUpload.setAttribute("name", "pic"); uploadBut.setAttribute ("type", "submit"); uploadBut.setAttribute ("value", "Upload"); form.appendChild(fileUpload); form.appendChild(uploadBut); dlgContent.appendChild(form);