Posting Files with AJAX


Well it’s not actually AJAX, but mimics very well.

Consider a scenario where you need to submit files using AJAX because the files are too large to be handled by normal posting and the user would try to cancel the file post while he waits. You could consider the same scenario but with you wanting the user to do something while he waits for the file upload.

As you probaly know, posting files through AJAX is not that easy, but, there is a very simple trick that you can use with very simple Javascript: POST to an IFRAME.

The first time that I have heard about this I tought that was very weird, but you know, why not give it a try.

To post to an Iframe is simple. Create your FORM as you would usally do and add a TARGET attribute to it with the IFRAME NAME set on it. Now create the IFRAME with the DISPLAY and VISIBILITY style set to none and hidden and add set the WIDTH and HEIGHT to 1px each.

Add a submit button on the form and you are good. Everything inside the form will be posted to the IFRAME, but for the user, it will be like he had never left the page.

Simple cool trick.

For faster help, here is the code:

<form id=”frm” name=”frm” method=”post” action=”postHandler.php” enctype=”multipart/form-data” target=”postIframe”>

<input type=”file” name=”myFile” id=”myFile” value=”” size=”30″ /><br />
<input type=”button” id=”btnSubmit” name=”btnSubmit” value=”Upload File” onClick=”document.frm.submit();” /><br />


<iframe name=”postIframe” id=”postIframe” style=”width:1px; height:1px;display:none;visibility:hidden;”></iframe>


About mcloide

Making things simpler, just check: View all posts by mcloide

3 responses to “Posting Files with AJAX

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: