I have created a form using JavaScript like
//Create a form
var form = document.createElement('FORM');
form.name = 'myForm';
form.method = 'POST';
form.action = 'SomePath';
//Create a hidden filed
var hidden = document.createElement('INPUT');
hidden.type = 'HIDDEN';
hidden.name = 'MyHiddenField';
hidden.value = 'MyHiddenFieldValue';
form.appendChild(hidden);
//Submit form
form.submit();
When the script executes. All statements executes without any error. But form is not actually submitted.
However when I append it document. like
document.getElementsByTagName('body')[0].appendChild(form);
//Submit form
form.submit();
Everything works fine. My question is Why do I need to append form to body? Am I missing something.
EDIT: It worked without appending form to body
in chrome.
I have created a form using JavaScript like
//Create a form
var form = document.createElement('FORM');
form.name = 'myForm';
form.method = 'POST';
form.action = 'SomePath';
//Create a hidden filed
var hidden = document.createElement('INPUT');
hidden.type = 'HIDDEN';
hidden.name = 'MyHiddenField';
hidden.value = 'MyHiddenFieldValue';
form.appendChild(hidden);
//Submit form
form.submit();
When the script executes. All statements executes without any error. But form is not actually submitted.
However when I append it document. like
document.getElementsByTagName('body')[0].appendChild(form);
//Submit form
form.submit();
Everything works fine. My question is Why do I need to append form to body? Am I missing something.
EDIT: It worked without appending form to body
in chrome.
- 1 I think because then it will be added to the DOM, else your only creating new elements but not appending them to the DOM. You could also use document.body.appendChild(form); – Rob Angelier Commented Feb 26, 2014 at 9:07
- somebody here had this same problem way back in 2008... – user3526 Commented Aug 8, 2015 at 22:31
2 Answers
Reset to default 5Without knowing for sure, I would conjecture that the creators of DOM and Javascript saw form
as an inherently document-dependent entity, and didn't account for the possibility of being able to submit a form that is not attached to the DOM.
Anyway, if you just don't want it seen, then before you attach the form, do
form.style.visibility = 'hidden';
What submit method does, pletely depends on being included in the DOM:
Standard use of HTML forms requires loading the page to which the data is sent, which means the entire page is refreshed.
it actually need to be in the DOM to be sent in a page load.
By the time Ajax showed up we used hidden iframes to send a form without the actual page gets refreshed.
But if you want to use form elements, to create a Http call without refreshing the page, you need to do it via JavaScript.
This is one of the best references out there which would help you, decide how to do what you want using html form tag:
Sending forms through JavaScript