Jason Deacon Team : Web Development Tags : Web Development

Uploading a file over an Ajax postback

Jason Deacon Team : Web Development Tags : Web Development

None of my usual long-winded ranting this time around. Code. Just code.

Many people don't realise that most modern browsers are capable of uploading a file over an Ajax postback, something which can come in handy when you want to maintain a positive user experience and not resort to flash-based or html5 based uploaders.

How

 

1) The markup

Submit!

 

2) The Javascript

The magical stuff is the 'var dataString = new FormData(myForm.get(0))' line, in browsers that support it (more on that later).

$(function () { 	$('.form-submit-button').click(function () { 		var myForm = $(this).closest("form"); 		if (myForm.valid()) {  			if (typeof(FormData) === 'function') {  				var dataString = new FormData(myForm.get(0));  				$.ajax({ 					url: myForm.prop("action"), 					type: 'post', 					data: dataString, 					processData: false, 					contentType: false, 					success: function(result) { 						// handle the success result, set the html back in to a visible container 						myForm.closest(".form-container").html(result); 					}, 					error: function(jqXHR, textStatus, errorThrown) { 						// handle your error 						alert(errorThrown); 					} 				}); 				// it is important to return false in order to 				// cancel the default submission of the form 				// and perform the AJAX call 				return false; 			} else { 				// do a regular postback 				myForm.submit(); 				return false; 			} 		} 	}); });

 

3) Server side

Just handle the request as you normally would, nothing special here.

Browser Support

 

The central object for this mechanism is the FormData class in javascript. If it is not declared by the browser then you will not be able to upload files using AJAX. In that scenario you can choose to revert to flash-based uploaders or some other equally outdated method, but once you see the browser compatibility chart below you might just choose to fall back to a regular old full page postback.

  • Chrome 7+
  • Firefox 4.0+
  • IE 10+ (Haha)
  • Opera 12+
  • Safari 5+

 

So basically it's only the out of date IE users that will need the fallback behaviour, so you will need to decide for yourself based on the target audience of your site.