Created
November 20, 2013 11:21
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input id="avatar" type="file" name="avatar" /> | |
<button id="upload" value="Upload" /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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