Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RimonEkjon/4fc8e1581d6e92b18111 to your computer and use it in GitHub Desktop.
Save RimonEkjon/4fc8e1581d6e92b18111 to your computer and use it in GitHub Desktop.
/*
* 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