Friday, June 12, 2009

Dynamic IFrames As Form Targets

Sometimes you need to submit a form through some hidden iframe, usually when you're trying to monkey an ajax request for a file uploading.

Usually you just render an iframe element along with the form in the html code and assign the target attribute of the form. Something like this

<form target="my-iframe">.....</form>
<iframe name="my-iframe"></iframe>

It works, but in cases when you try do the same thing dynamically with javascript. Say to wire some additional fancy callbacks or something. Say like that.

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.id = iframe.name = 'my-iframe';
window['my-iframe'].onload = function() {...};

var form = document.getElementById('my-form');
form.target = iframe.id;
form.submit();

This thing looks generally correct, but unfortunately won't work.

I'm not sure why, but I do know the way how to deal with it.

The trick is simple, dirty and cross-browsing. Just how we like it.

var div = document.createElement('div');
document.body.appendChild(div);
div.innerHTML = '<iframe id="my-iframe" name="my-iframe"></iframe>';
var iframe = document.getElementById('my-iframe');
iframe.addEventListener('load', function() {....}, false);
// or for IE
iframe.attachEvent('onload', function() {....});

var form = document.getElementById('my-form');
form.target = iframe.id;
form.submit();

This thing is perfectly works in all the modern browsers and old IEs.

And for the end, there is even better way. Try the new RightJS framework. Then the same thing will look like this.

$('my-form').send();

This is pretty much it. Have a good one.

2 comments:

Johnrock Chou said...

have you try this way?
document.getElementById('my-iframe').onload = function() {...};

window['my-iframe'] and document.getElementById('my-iframe') is not the same object.

Nikolay V. Nemshilov said...

As far as I recall it now, it doesn't work in IE