Skip to content

Instantly share code, notes, and snippets.

@jhogervorst
Last active January 1, 2016 15:49
Show Gist options
  • Save jhogervorst/8166385 to your computer and use it in GitHub Desktop.
Save jhogervorst/8166385 to your computer and use it in GitHub Desktop.
Function to easily submit forms with file uploads using AJAX in jQuery Mobile.
/*
* jQuery.ajaxEnvironment.js
* https://gist.github.com/jhogervorst/8166217
*
* jQuery.Mobile.ajaxUpload.js
* https://gist.github.com/jhogervorst/8166385
*
* Copyright (C) 2013 Jonathan Hogervorst. All rights reserved.
* This code is licensed under MIT license.
*/
(function($) {
$.ajaxEnvironment = function(settings, block) {
var originalSettings = $.ajaxSetup();
var restoredSettings = {};
$.each(settings, function(key) {
restoredSettings[key] = originalSettings[key];
});
$.ajaxSetup(settings);
block();
$.ajaxSetup(restoredSettings);
};
$.mobile.ajaxUpload = {};
$.mobile.ajaxUpload.changePage = function(form, options) {
form = $(form);
$.ajaxEnvironment({
contentType: false,
processData: false,
}, function() {
$.mobile.changePage(form.attr('action'), {
data: new FormData(form[0]),
type: form.attr('method'),
});
});
};
})(jQuery);

jQuery.Mobile.ajaxUpload

Function to easily submit forms with file uploads using AJAX in jQuery Mobile. Not all browsers support file uploads via AJAX!

Usage

<form action="upload.php" method="post" enctype="multipart/form-data" id="myForm">
	<input type="file" name="my_file" id="my_file">
</form>

<script>
	$('form#myForm').on('submit', function(event) {
		$.mobile.ajaxUpload.changePage(this);
		return false; // prevent regular submit
	});
</script>

Compatibility

This code has been tested with jQuery 1.9.1 and jQuery Mobile 1.3.2 in Safari on Mac.

License

This code is licensed under MIT license.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment