Guest User

Untitled

a guest
Aug 17th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. Hidden form file POST in javascript
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="utf-8">
  6. <title>hidden form post demo</title>
  7. </head>
  8.  
  9. <body>
  10. <script>
  11.  
  12. //helper function to create the form
  13. function getNewSubmitForm(){
  14. var submitForm = document.createElement("FORM");
  15. document.body.appendChild(submitForm);
  16. submitForm.method = "POST";
  17. submitForm.enctype = "multipart/form-data";
  18. return submitForm;
  19. }
  20.  
  21. //helper function to add elements to the form
  22. function createNewFormElement(inputForm, inputType, elementName, elementValue) {
  23. var inputElement = document.createElement("INPUT");
  24. inputElement.name = elementName;
  25. inputElement.type = inputType;
  26. try {
  27. inputElement.value = elementValue;
  28. } catch(err) {
  29. alert(err.description);
  30. }
  31. inputForm.appendChild(inputElement);
  32. return inputElement;
  33. }
  34.  
  35. //function that creates the form, adds some elements
  36. //and then submits it
  37. function createFormAndSubmit(){
  38. var submitForm = getNewSubmitForm();
  39. var selectedFileElement = document.getElementById("selectedFile");
  40. var selectedFile = selectedFileElement.files[0];
  41. createNewFormElement(submitForm, "HIDDEN", "xml", "my xml");
  42. createNewFormElement(submitForm, "FILE", "selectedFile", selectedFile);
  43. submitForm.action= "my url";
  44. submitForm.submit();
  45. }
  46.  
  47. </script>
  48.  
  49.  
  50. <div id="docList">
  51. <h2>Documentation List</h2>
  52. <ul id="docs"></ul>
  53. </div>
  54.  
  55. <input type="file" value="Click to create select file" id="selectedFile"/>
  56. <input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()"/>
  57. </body>
  58.  
  59. </html>
  60.  
  61. <form method="post" enctype="multipart/form-data" action="myurl">
  62. <input type="file" value="Click to create select file" name="selectedFile" />
  63. <input type="hidden" name="xml" value="my xml" />
  64. <input type="submit" value="Click to create form and submit" />
  65. </form>
  66.  
  67. <form ... onsubmit="addMoreinputs();" id="aForm">
  68. ...
  69. <script>
  70. function addMoreInputs(){
  71. var form = document.getElementById("aForm");
  72. // ...create and append extra elements.
  73. // once the function has finished, the form will be submitted, because
  74. // the input[type=submit] element has been clicked.
  75. }
Add Comment
Please, Sign In to add comment