How to upload a file using Ajax on POST?
The below method works for me, it will submit all form value as serialize()
. You will get all form input's inside request.POST
and logo request.FILES
Try this:
$(document).on('submit', '#creationOptionsForm', function(e){
e.preventDefault();
var form_data = new FormData($('#creationOptionsForm')[0]);
$.ajax({
type:'POST',
url:'/designer/results/',
processData: false,
contentType: false,
async: false,
cache: false,
data : form_data,
success: function(response){
}
});
});
Update:
basically async:false
will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.
While cache
will force browser to not cache uploaded data to get updated data in ajax request
Official Documentation here
Looking back, the older answer is unpractical and not recommended. asnyc: false
pauses the entire Javascript to simply upload a file, you are likely firing other functions during the upload.
If you are using JQuery solely for the use of ajax
, then I recommand using axios
:
const axios = require('axios');
var formData = new FormData();
formData.append('imageFile', document.querySelector('#image_file').files[0]);
axios({
method: 'post',
url: 'your_url',
data: formData,
headers: {
"X-CSRFToken": CSRF_TOKEN, # django security
"content-type": "multipart/form-data"
}
}).then(function (response) {
# success
});
Axios Documentation
Jquery/Ajax answer:
var formData = new FormData();
formData.append('imageFile', $('#image_file')[0].files[0]);
formData.append('csrfmiddlewaretoken', CSRF_TOKEN); # django security
$.ajax({
url : 'your_url',
type : 'POST',
data : formData,
processData: false,
contentType: false,
success : function(data) {
# success
}
});
Jquery/Ajax Documentation