Our highest priority is to satisfy the customer through early and continuous delivery of valuable and working software.

Friday, May 4, 2007

File upload through AJAX

Not Possible.

because AJAX is nothing more than a faster and more elegant way to do a client side interface online. It is designed for client-side programming. It doesn't actually provide any server-side processing capabilities.

AJAX doesn't actually post forms to the server, it sends selected data to the server in the form of a POST or GET request. As javascript is not capable of grabbing the file from the users machine and sending it to the server, it's just not possible with AJAX. You have to resort to regular old form submit.

If you have read/seen it somewhere, then it is not through AJAX. File uploading occurs through an iframe in this case. You have to use a iframe to upload the files. So, you can use iframe to asynchronous upload (Like AJAX , but its not AJAX).

How file uploading is done in Gmail? Use following JavaScript function, if you want to achieve same functionality.


<script language="Javascript">
function fileUpload(form, action_url, div_id)
// Create the iframe...
var iframe = document.createElement("iframe");
iframe.setAttribute("style","width: 0; height: 0; border: none;");

// Add to document...

iframeId = document.getElementById("upload_iframe");

// Add event...
var eventHandler = function() {

if (iframeId.detachEvent)
iframeId.detachEvent("onload", eventHandler);
iframeId.removeEventListener("load", eventHandler, false);

// Message from server...
if (iframeId.contentDocument) {
content = iframeId.contentDocument.body.innerHTML;
} else if (iframeId.contentWindow) {
content = iframeId.contentWindow.document.body.innerHTML;
} else if (iframeId.document) {
content = iframeId.document.body.innerHTML;

document.getElementById(div_id).innerHTML = content;

// Del the iframe...
setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);

if (iframeId.addEventListener)
iframeId.addEventListener("load", eventHandler, true);
if (iframeId.attachEvent)
iframeId.attachEvent("onload", eventHandler);

// Set properties of form...
form.setAttribute("action", action_url);

// Submit the form...

document.getElementById(div_id).innerHTML = "Uploading...";

<!-- index.php could be any script server-side for receive uploads. -->
<input type="file" name="datafile" /></br>
<input type="button" value="upload" onClick="fileUpload(this.form,'index.php','upload'); return false;" >
<div id="upload"></div>


No comments:

Post a Comment