Skip to content

Instantly share code, notes, and snippets.

@w3villa
Created November 20, 2013 11:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w3villa/7561604 to your computer and use it in GitHub Desktop.
Save w3villa/7561604 to your computer and use it in GitHub Desktop.
Uploading files/image with Ajax & Jquery, without submitting a form. Read complete blog post at http://blog.w3villa.com/websites/uploading-filesimage-with-ajax-jquery-without-submitting-a-form/
<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />
$(document).on("click", "#upload", function() {
var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
form_data.append("user_id", 123) // Adding extra parameters to form_data
$.ajax({
url: "/upload_avatar",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post'
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment