Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Hidden form file POST in javascript
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>hidden form post demo</title>
- </head>
- <body>
- <script>
- //helper function to create the form
- function getNewSubmitForm(){
- var submitForm = document.createElement("FORM");
- document.body.appendChild(submitForm);
- submitForm.method = "POST";
- submitForm.enctype = "multipart/form-data";
- return submitForm;
- }
- //helper function to add elements to the form
- function createNewFormElement(inputForm, inputType, elementName, elementValue) {
- var inputElement = document.createElement("INPUT");
- inputElement.name = elementName;
- inputElement.type = inputType;
- try {
- inputElement.value = elementValue;
- } catch(err) {
- alert(err.description);
- }
- inputForm.appendChild(inputElement);
- return inputElement;
- }
- //function that creates the form, adds some elements
- //and then submits it
- function createFormAndSubmit(){
- var submitForm = getNewSubmitForm();
- var selectedFileElement = document.getElementById("selectedFile");
- var selectedFile = selectedFileElement.files[0];
- createNewFormElement(submitForm, "HIDDEN", "xml", "my xml");
- createNewFormElement(submitForm, "FILE", "selectedFile", selectedFile);
- submitForm.action= "my url";
- submitForm.submit();
- }
- </script>
- <div id="docList">
- <h2>Documentation List</h2>
- <ul id="docs"></ul>
- </div>
- <input type="file" value="Click to create select file" id="selectedFile"/>
- <input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()"/>
- </body>
- </html>
- <form method="post" enctype="multipart/form-data" action="myurl">
- <input type="file" value="Click to create select file" name="selectedFile" />
- <input type="hidden" name="xml" value="my xml" />
- <input type="submit" value="Click to create form and submit" />
- </form>
- <form ... onsubmit="addMoreinputs();" id="aForm">
- ...
- <script>
- function addMoreInputs(){
- var form = document.getElementById("aForm");
- // ...create and append extra elements.
- // once the function has finished, the form will be submitted, because
- // the input[type=submit] element has been clicked.
- }
Add Comment
Please, Sign In to add comment