Can anybody tell me Why I click on button to submit form -> it works, but when I use javascript to auto submit -> it failed ?

I have this form on aaa.com, it submit to bbb.com/result.jsp (another domain)

<form id="myForm" name="myForm " method="post" action="www.bbb..com/result.jsp">
<input name="var01" value="var01 ">
<input name="var02" value="var02 ">
 <input type="submit" name="searchButton" value="Search">
</form>

Manually click on Search button, result.jsp works fine.

When I added following script, result.jsp page doesn’t work

<script>
document.getElementById("myform").submit();
</script>
Member Avatar for Rahul47

Try action="www.bbb.com/result.jsp". In your code there is an extra dot (.) after bbb.

@Rahul47, I suspect that bbb.com is just a placeholder, not the real action URL.

@Dinh Nguyen-

Are you trying to submit the form when the page loads? If so...

<form id="myForm" name="myForm " method="post" action="result.jsp" />
   <input name="var01" value="var01 " />
   <input name="var02" value="var02 " />
   <input type="submit" name="searchButton" value="Search" />
</form>

<script>
    window.onload = function() {
        document.getElementById("myForm").submit();
    }
</script>

Or... if you want to be able to sumit the form using another element, say a button outside the form, you can use the onclick event to call a function...

<form id="myForm" name="myForm " method="post" action="result.jsp" />
   <input name="var01" value="var01 " />
   <input name="var02" value="var02 " />
   <input type="submit" name="searchButton" value="Search" />
</form>

<p><input type="button" name="miscBtn" onclick="formSubmit()" value="Submit the Form!" /></p>

<script>
   function formSubmit(){
      document.getElementById("myForm").submit();
   }
</script>
<script>
    window.onload = function() {
        document.getElementById("myForm").submit();
    }
</script>

Yes, I want to submit the form when page load, but how can I pass button click event with it? for ("myForm").submit() doesn't tell which button (or event action) should be performed?

Huh? If you want the form to be submitted on page load, you don't need a button to trigger the event.

In the example I provided it is handled by window.onload.

Maybe I'm not understanding what it is you want to happen.

Member Avatar for iamthwee

And consider using Jquery.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.