views:

777

answers:

3

I am trying to get post a form to a hidden, dynamically inserted iframe, but in Internet Explorer the form submission opens in a new window.

var iframe = document.createElement('iframe');
iframe.name = 'hidden_iframe';
iframe.className = 'NotVisible';
iframe.id = 'hidden_iframe';
document.body.appendChild(iframe);

var my_form = document.getElementById('my_form');
my_form.target = 'hidden_iframe';

This works in Firefox but not IE.

+4  A: 

Apparently you need to include the name in the call to createElement. This works in IE and causes an exception in standards compliant browsers. We get:

var iframe;
try {
    iframe = document.createElement('<iframe name="hidden_iframe">');
} catch (ex) {
    iframe = document.createElement('iframe');
    iframe.name='hidden_iframe';
}

iframe.className = 'NotVisible';
iframe.id = 'hidden_iframe';
document.body.appendChild(iframe);

var my_form = document.getElementById('my_form');
my_form.target = 'hidden_iframe';
lambacck
+1 for finding something this awful in IE. Which version of IE? 6? 7? 8?
scraimer
Required for IE 6 and 7. IE 8 works either way.
lambacck
Great fix, never would've thought of it. Should've done the least intuitive thing I could think of for IE.
brad
A: 

Could this not be more easily accomplished using an a AJAX submit? The iframe approach you're presenting is very hackish and prone to lots of issues.

Here is a JQuery Form plugin that makes doing AJAX submits easy by handling all the serialization of the form values for you.

Soviut
I need to get parts of the resulting HTML document. Also I don't think your JQuery Form plugin will work for file uploads (which is the main argument for using the presented technique).
lambacck
jQuery Forms works for file uploads because it uses an IFRAME behind the scenes whenever there is a file input in the form.
Sam
Interesting. Even if that's the case, JQuery Forms works across multiple browsers out of the box. Secondly, you can specify callbacks both pre and post submit, so you could return an an html ajax response on submit.
Soviut
Since I am not using jQuery I still needed a solution. I am not using jQuery because I have an existing code base using MochiKit and I don't want to add yet another 19k resource to the page and this particular page is using Google Maps API so I am not even using MochiKit.Also, I think it is important to know what is going on behind the scenes in these frameworks.
lambacck
Agreed, it is important to know, but at the same time, its good to leverage other people's existing work so you're not reinventing the wheel every time.
Soviut
A: 

Thanks a lot I was also havinbg same problem in post to iframe and your code 'iframe = document.createElement('');' fixed it '

neha