Reputation: 45
I am trying to submit a form to an iframe both of which are constructed dynamically in my project using javascript.
<script>
document.querySelector('iframe').setAttribute('id', iframeId);
document.getElementById(iframeId).setAttribute('name', target);
document.getElementById(iframeId).setAttribute('width', width);
document.getElementById(iframeId).setAttribute('height', height);
document.querySelector('form').setAttribute('id', id);
document.getElementById(id).setAttribute('target', target);
document.getElementById(id).setAttribute('action', actionURL);
document.getElementById(id).submit();
<script>
This is how it looks later in the browser Web Inspector.
<iframe id="my_frame" name="my_frame" width="700" height="400">
<p>Your browser does not support iframes.</p>
</iframe>
<form id="my_form" target="my_frame" action="http://localhost:8080/MyProject/loadService" method="POST" style="display: none;">
<input type="hidden" name="userId"/>
<input type="hidden" name="locale"/>
</form>
This works well for me in Firefox but in Chrome it opens a new tab. I tried the solution given here but it didn't resolve the issue. Can anyone please suggest what is missing?
Upvotes: 1
Views: 3174
Reputation: 600
Remove the iframe from your html and try doing like this:
//Create the iframe, set its attributes and append it before the form
var iframe = document.createElement('iframe');
iframe.name = 'my_frame';
iframe.id = 'my_frame';
iframe.width = '400';
iframe.height = '700';
var form_element = document.getElementById('my_form');
form_element.parentNode.insertBefore(iframe, form_element);
//Submit form to iframe
document.getElementById('my_form').submit();
Upvotes: 4
Reputation: 1246
I had the same issue. I followed this post which fixed it for me. try dynamically generating the iframe, and make sure to set the name/id that will be targeted by the form BEFORE you append the iframe to the DOM.
example:
iframe = document.createElement('iframe');
iframe.name = 'target_name';
iframe.id = 'target_name';
// now append to DOM, ideally to a container element
document.body.appendChild(iframe);
Upvotes: 3
Reputation: 322
This post suggests adding the target-attribute of the form dynamically before submitting the form.
Since you are creating both – the form and the iframe – dynamically, have you tried creating and adding the iframe to the DOM before the form? Maybe the target-id has to exist on form-creation-time for it to work correctly.
Upvotes: 0