Skip to content

Instantly share code, notes, and snippets.

@pheisiph
Created May 15, 2012 10:25
Show Gist options
  • Save pheisiph/2700643 to your computer and use it in GitHub Desktop.
Save pheisiph/2700643 to your computer and use it in GitHub Desktop.
File Upload with Ajax
$form = $("#edit_item");
// Build the FormData object with some Rails-specific attributes
var formData = new FormData($form[0]);
formData.append('utf8','✓')
formData.append('_method', 'put'); // editing existing record
formData.append('authenticity_token', AUTH_TOKEN);
$.ajax({
url: $item.attr('data-uri'), // or # form action attribute
type: 'POST',
data: formData,
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',function(e) {
if (e.lengthComputable){
console.debug({value:e.loaded,max:e.total});
}
}, false); // for handling the progress of the upload
}
return myXhr;
},
success: function() { console.debug("success"); },
error: function() { console.debug("error"); },
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment