Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How send a form with Javascript when input name is "submit"?

Question: How can you send a form with Javascript if one form input has the name submit?

Background: I am redirecting the user to another page with a hidden HTML form. I cannot change name on the (hidden) inputs, since the other page is on another server and the inputs need to be exactly as they are. My HTML form looks like this:

<form id="redirectForm" method="post" action="http://www.example.com/">
  <input name="search" type="hidden" value="search for this" />
  <input name="submit" type="hidden" value="search now" />
</form>

I use the following javascript line to send the form automatically today:

document.getElementById('redirectForm').submit();

However, since the name of one input is "submit" (it cannot be something else, or the other server won't handle the request), document.getElementById('redirectForm').submit refers to the input as it overrides the form function submit().

The error message in Firefox is: Error: document.getElementById("requestform").submit is not a function. Similar error message in Safari.

like image 998
AndersTornkvist Avatar asked Jan 04 '12 15:01

AndersTornkvist


People also ask

How do you call a JavaScript function when a form is submitted?

To call and run a JavaScript function from an HTML form submit event, you need to assign the function that you want to run to the onsubmit event attribute. By assigning the test() function to the onsubmit attribute, the test() function will be called every time the form is submitted.

Can form data be sent via JavaScript?

HTML forms can send an HTTP request declaratively. But forms can also prepare an HTTP request to send via JavaScript, for example via XMLHttpRequest .


2 Answers

Worth noting: It's often a lot easier to just change the input name to something other than "submit". Please use the solution below only if that's really not possible.

You need to get the submit function from a different form:

document.createElement('form').submit.call(document.getElementById('redirectForm'));

If you have already another <form> tag, you can use it instead of creating another one.

like image 171
SLaks Avatar answered Oct 17 '22 23:10

SLaks


Use submit() method from HTMLFormElement.prototype:

HTMLFormElement.prototype.submit.call(document.getElementById('redirectForm'));
like image 30
Michał Perłakowski Avatar answered Oct 18 '22 00:10

Michał Perłakowski