Saturday, January 8, 2011

Ajax Upload working example

My application is a little different but the principle should work for most situations.

Here is the coolest ajax upload code, it includes multi upload, continues (meaning you can keep uploading with it after one or multiple you can upload again) it has progress-bar and even the amazing drag-and-drop in firefox and chrome browsers (why use any other browser anyway right?)

Anyway the usual instructions are to include this code where you want the upload button to appear:

<div id="file-uploader-demo1">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
</noscript>      
</div>


Keep in mind the id of the div, the javascript to include can be done anywhere at the top header or even before this div.

Now here is where I differ from the author's instructions because of my needs; place this function included ajax javascript files:

function createUploader(){          
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader-demo1'),
action: 'upload.php',
debug: true
});        
}

And since the way I generate the forms, the user clicks on a button which triggers onclick and the onreadystatechange will generate responsetext inside the javascript will not execute as usual so I simply add :
setTimeout('createUploader()', 500);

after the:

xmlHttp.onreadystatechange=thefunc;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);

<place above line here>

So this setTimeout waits for half a second and loads the function of the upload button and iframes associated all on it's own!

Hope someone finds this useful, leave a comment if you do, or have questions, etc.

No comments: