Ajax: Upload a file through ajax ( without page refresh)

January 2, 2011 | In: ajax, php, web development

In most cases we need to upload something on server without refreshing the page. for example we want to upload an image from popup window. But it will refresh the page and we will lost our popup and its content… so for this type of problems we providing an attractive code for upload a files on server through AJAX technology from webtoolkit.

<script src="webtoolkit.aim.js" type="text/javascript"></script>
<form action="index_processing.php" method="post">
	<div><label>File:</label><input name="form[file]" type="file" /></div>
	<div><input type="submit" value="SUBMIT" /></div>
</form>
AIM = {
 
	frame : function(c) {
 
		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '';
		document.body.appendChild(d);
 
		var i = document.getElementById(n);
		if (c &amp;&amp; typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}
 
		return n;
	},
 
	form : function(f, name) {
		f.setAttribute('target', name);
	},
 
	submit : function(f, c) {
		AIM.form(f, AIM.frame(c));
		if (c &amp;&amp; typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	},
 
	loaded : function(id) {
		var i = document.getElementById(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") {
			return;
		}
 
		if (typeof(i.onComplete) == 'function') {
			i.onComplete(d.body.innerHTML);
		}
	}
 
}

Souce code for index_processing.php :

	print_r($_REQUEST['form']);