Ajax File Upload
You might have seen Ajax File Uploading in some sites. The basic idea is to upload a file without refreshing the page. Some sites go even further by providing details on how much percentage is uploaded, etc. It is very easy to achieve this effect using javascript.
First off, I did not like using the term 'Ajax' when describing this method. But there is no other word that can be used. And this method fits within my definition of Ajax - "Sending or receiving data from the server without refreshing the page.". So I will name this method Ajax file upload.
Theory
The basic idea behind this effect is to redirect a form's action into a hidden IFrame. So, when the form with the file field is submitted, the result will appear in a IFrame. But since it is hidden, the user will not see it. This effect is achieved using the 'target' attribute of the Form tag.
See the small squire? That is the IFrame. Typically, it will be hidden.
Code
(X)HTML
<form id="file_upload_form" method="post" enctype="multipart/form-data" action="upload.php">
<input name="file" id="file" size="27" type="file" /><br />
<input type="submit" name="action" value="Upload" /><br />
<iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
JavaScript
function init() {
document.getElementById('file_upload_form').onsubmit=function() {
document.getElementById('file_upload_form').target = 'upload_target'; //'upload_target' is the name of the iframe
}
}
window.onload=init;
PHP
This should be in upload.php - the action of the form.
<?php
include('../../../common.php');
upload('file','.','txt,jpg,jpeg,gif,png');
The code to upload the file must be given here. I used one of my custom functions to upload the file - it is not a native PHP function. Needless to say, this is not restricted to PHP - you can use any server side language here.
Update: Part two - Ajax File Upload Response Handling

Comments
it will be interesting to see how it could give details on how much percentage is uploaded?
cheers
The OP of the comment that you bashed is absolutely correct. Everything about this page indicates that it's an AJAX file upload example. Look at the name of the page if you don't believe me. Even the title and first paragraph indicate that this uses the AJAX methodology to upload a file.
There is nothing asynchronous about this upload function. He has simply hidden all of the refresh bits within an Iframe and wrapped the name AJAX around it. Look at the form code. It's still a post function like every other type of non AJAX file upload. Here is the source if you are still in disbelief :
<form id="file_upload_form" action="upload.php" enctype="multipart/form-data" method="post" target="upload_target">
<input id="file" type="file" size="27" name="file"/>
<br/>
<input type="submit" value="Upload" name="action"/>
<br/>
<iframe id="upload_target" style="border: 1px solid rgb(204, 204, 204); width: 100px; height: 100px;" src="" name="upload_target">
</iframe>
</form>
There is nothing AJAX about this at all. This page should have been renamed something like "how to upload files using iframes" or some such.
TO THE AUTHOR:
Your definition - "Sending or receiving data from the server without refreshing the page." is essentially correct. Your implementation of it however fails completely. You are still doing a page refresh, only you are doing it in an iframe.
That said, I can tell you that this really is not a bad example of how to upload a file using iframes. Perhaps you could rename and reformat this page so as to show it for what it really is, rather than try to bullshit your way through.
About AJAX doubts:
For security reasons, JavaScript CANNOT ACCESS any local hard drive (imagine your machine exposed to anyone only because you accept JavaScript execution in your browser only to see user friendly pages).
Actually, iFrames manage asynchronous calls, you can figure it out since you can use your current page while your browser is downloading content to an iFrame.
The name AJAX served us to find an asynchronous way to get this article, other way we shouldn't find any article to upload files without refreshing the page.
Have a nice day.
This is simply not true. Javascript cannot access any local hard drive in browsers, unless that user is browsing with IE, in which case you certainly _can_ access the local machine via the FileSystemObject, instantiated by a proper api call using the ActiveX interface.
Know, before you blurt.
To all people that say this is not ajax:
Guys I now it is painful for you to see how the autor of this article with few simple lines of html code do the same thing that you usually do with hundred of lines complicated javascript code, and I very sorry for you, but who care whether this is ajax or not, if the result is the same?!
There are cases where using ajax javascript objects is a must, but for this case and for many other cases this ajax approach is perfect.
So we must be grateful to autor for sharing it with us.
You must not blame the autor for thing you cannot understand or accept.
This is some other way to submit form. Sorry you can't say it AJAX.
And it is correct to call it AJAX, as AJAX 'calls' can be implemented either with XMLHttpRequests or with IFrames. In some frameworks you even get to choose which method is used to make the 'calls'.
Plz wud u explain a context in which this code wud be of use.
This is a real life scenario. I just used this example for this situation. My predecessor got around this problem with flash forms, which are slow to load and consequently slow down my application (the site in question has more in common with a desktop app than a normal web page). This is a much better solution IMHO.
I was wondering how I might do this with httpRequest instead as well.
If someone would be so kind as to help me my E..!!(E($& - Mai1 is
dan ...-~~~at~~~-- danmckinnon )*)*&)* --~~~d0t~~-- net
(and of coarse ignore all the funny charecters, it's to avoid bots from grabbing my e-mail address)
This doesn't seem to be working in IE.
Any reason for that?
Cheers
Thanks for your reply
I'm using version 6.0
Cheers
Bruno
follow the following like you can find useful code
www.webtoolkit.info/ajax-file-upload.html
www.seemysites.net/projFolder/uploader/
I am also not able to get any of the examples of this method (i.e. iframes) to work with IE 6. If anyone has been able to do it please post it here.
Since Ajax stands for for "Asynchronous JavaScript and XML", I have a feeling there is no way to do file uploads since JSON and XML can only work with text going to and coming from the server. I still can't find a way to send a file over using pure AJAX. Please prove me wrong if you can.
Thank you it is realy very good idea, i used it, it is woking well
thank you
Praveen
Nice work.
BTW - The "not Ajax" people: The _point_ of Ajax is to not have to reload the page, regardless of the technique used.
& Ajax Design patterns , and i am sure that u have used that the basics quiet right , in all a simple idea but with great impact.
I am also looking for the progress bar and State Complete Callbacks after the file upload process.
Thanx Again.
Thanks for the script!.
it is using ajax
it has no refresh and using the object XMLHTTPRequest.
this is the basic thing of ajax.
what you are using is the old version of web before Ajax method is well known.
many web programmer using iframe to reduce the refreshed page.
regrds,
ngonar
I don't know what I'm doing wrong: the form gets submitted and the upload.php gets loaded, but no into the iframe, it's displayed normally as a new page.
Any suggestions?
Thanks in advance!
Regard siner
frm = document.createElement("iframe")
document.body.appendChild(frm)
.
.
.
doc = document.createElement("form")
document.body.appendChild(doc)
doc.enctype = doc.encoding = "multipart/form-data" // ensure it will work with IE and FF
doc.action = "_hnew"
doc.method = "post"
doc.target = "frm"
.
.
.
it works fine with FireFox, IE makes everythink ok except for the fact that it opens a new window with a blank page inside it, how can I get rid of that annoying extra window???
<form id="file_upload_form" method="post" enctype="multipart/form-data" target="upload_target" >
<iframe id="upload_target" name="upload_target" <strong> src="upload.php" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
Setting a target in the HTML works fine too :?
In the [POST] tag, there are nothing inside,
in the [Response] Tag, there are a error "no file specified"
the request seems execute more than one time
i was searching for this since long time..
Is there really no other alternative to "Ajax file upload" without using iFrame... ?
anyone know is this will work at all in IE, this "call back" is very handy. works everywhere except IE.
first of all THANKS :) (Hope i get this to work ;) )
I tryed everything, but it will not work ??
Im using Firefox 3.0.5
[code]
<form id='file_upload_form' method='post' enctype='multipart/form-data' action='php/misc/file_upload.php' target='upload_target'>
<input name='file' id='file' size='27' type='file' />
<input name='action' value='Upload Image' type='submit'>
<iframe id='upload_target' name='upload_target' src='php/misc/file_upload.php' style='border: 1px solid rgb(204, 204, 204); width: 400px; height: 100px;'></iframe>
</form>
[/code]
This is my Code.
When i click on Submit the whole page reloads and nothing habbens ??
Can someone help me, please.
I dont know where the promblem comes from !?
Thanks
Bouni
Please excuse my bad english ;)
this is what i have and works in FF 3.0.5
<form id="file_upload_form" method="post" enctype="multipart/form-data" action="upload_file.php" target="upload_target">
<input name="file" id="file" size="27" type="file" />
<input type="submit" name="action" value="Upload" />
<iframe id="upload_target" name="upload_target" src="" style="width:100px;height:100px;border:1px solid #ccc;"></iframe>
</form>
It's Ajax. Not AJAX, but Ajax. Now are the 'purists' content? :P. They should see Comet if they don't like this as Ajax. Comet's an even cruftier hack, but it does something otherwise impossible, even with Ajax. See below for Wikipedia's support.
"Ajax, or AJAX (Asynchronous JavaScript and XML), is a group of interrelated web development techniques used to create interactive web applications or rich Internet applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax has led to an increase in interactive animation on web pages.[1][2] Data is retrieved using the XMLHttpRequest object or through the use of Remote Scripting in browsers that do not support it. Despite the name, the use of JavaScript and XML is not actually required, nor do the requests need to be asynchronous.[3] The acronym AJAX has thus changed to the term Ajax, which does not represent these specific technologies.[4]"
It really doesn't matter if he uses an iframe or an XMLHttpRequest since the only difference between the two is that iframe actually renders the response and XMLHttpRequest doesn't (ofcouse you have a wider variety of settings for xmlhttprequest but for this case it does not matter).
The thing is, that even if he did this using XMLHttpRequest it wouldn't matter because the results will be the same.
Actually, you don't need to setup the init & onload function because IFRAME supports onLoad (perhaps you need it for older browser) and FORM also has target attribute which you can just point to the IFRAME.
joekuan.wordpress.com/2009/06/12/ajax-a-simplified-version-of-file-upload-form-using-iframe/
Hope this helps.
Is there a way so that we can check when response has been completed and also I want to check what is in the response.
My problem is: I post my form to slideshare api and get its response.Now this response comes into iframe and i am able to see it.but in coding i want to read this response.I have checked for innerHTML property of iframe using JavaScript but it is not working.The goal to achieve is to check the response and update text on the form so that user can see the status of uploading.
Any help.
Regards
Ulfat Hussain
Great work, thanks a lot.
But I have a problem with the back button of browsers (all of them).
The form that I'm using this method in is part of a series of pages - sort of a wizard - and after I upload a file the back button of the browser doesn't take me back to the previous page, it instead goes back before submitting the hidden iframe's form. so basically, users need to hit the browser's back button twice in order to go back to the previous page...
any way around this?
i do have a button on the page that sends them back properly (it's a link), but i don't want to ruin the browser's back button.
Thanks again
Roy.
Nice work Thanks
Nice code. Helps me a lot.
a, strong, em, b, i, code, pre, pandbrallowed. Other tags will be shown as code(< will become <). Urls, Line breaks will be auto-formated.