11 February 2009

Ajax (sort of) File Upload using LiveQuery/jQuery

I was building an Ajax only app, the kind that loads a minimal start page and stuffs empty divs with GET responses that are generated by partials just after the page loads. I needed to upload files.

There are many pages on the net explaining how to achieve this using a hidden iframe. To sum up the page uses a form not an XmlHttpRequest to POST the form and the results are loaded in the iframe which is the target for the POST response.

Most folks will not be that interested in the response. I was because the form created or edited a record and the file upload was a picture - part of the record. I needed to get the response, a 'show' partial of the record with a thumbnail out of the iframe and into a visible div.

There are not that many solutions out there (there is a jQuery forms one). I was using LiveQuery to maintain bound events on dynamic content anyway so I decided to use it again. This is what I came up with.


<script>
$(document).ready(function(){
...
$('iframe').livequery('load', function() {
var ifbodyhtml = $(this).contents().find('body').html()
if(ifbodyhtml.length > 0) {
$('#showcontact').html( ifbodyhtml )
}
return false
})
});
</script>
...
<div id="showcontact">

</div>
<iframe id="uploadtarget" name='uploadtarget' src='about:blank'></iframe>
When the page loads the jQuery $(document).ready() function loads various divs with content, one of which is the form in the 'showcontact' div.

The form has a target attribute of 'uploadtarget', so the LiveQuery is set to trap the load event of the iframe. This runs when the page is loaded and the iframe has no content so I've filtered that out. The response is taken from the iframe and put into the div.

That's it.

No comments: