Uploading files/image with Ajax & Jquery, without submitting a form

Uploading files/image with Ajax & Jquery, without submitting a form

Here is the code for uploading an image or file without submitting a form with Ajax. For this we will create object of FormData class and will append the properties of the file field in a attribute of FormData object, finally we will set the FormData object with the data key of ajax method of JQuery.

<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'
       })
})

We can get the parameters of file field by accessing the "file" key of the parameters hash. Sorry to say, but the FormData class is not supported in IE. :( If you are looking for a solution that works on all browsers have a look at Upload image without submitting form, works on all browsers.

Ishank Gupta

Related articles

Our two bytes give the latest technology trends and information that gives you fair information about the subject.

The Top 10 Must-Have Skills for Ruby on Rails Experts

The Top 10 Must-Have Skills for Ruby on Rails Experts

Ruby on Rails continues to be a preferred framework for developing scalable and maintainable web applications. For businesses seeking expert guid...
Why Combining Ruby on Rails with React.js Is a Game-Changer for Modern Web Apps

Why Combining Ruby on Rails with React.js Is a Game-Changer for Modern Web Apps

In the fast-paced digital world, businesses need more than just functional websites—they need fast, scalable, and user-friendly web applications....
5 Ways a Rails Consultant Can Save Your Time and Money

5 Ways a Rails Consultant Can Save Your Time and Money

If you’ve ever felt your web development project dragging on—costs mounting, deadlines slipping, and performance issues piling up—you’re not alone....

Cookie Preferences

We use cookies to deliver the best possible experience on our website. To learn more, visit our Privacy Policy. Please accept the cookies for optimal performance.Cookie Notice.