I am new to Flask and I have an easy question how to upload images using ajax in Flask, I tried the below code and it seems that the form data is empty and always stuck on response with the message "Presentation Not Found .." I tried mode different code and always failed
my code here :
@presentation.route('/presentation/updateImage',methods=['POST'])
@login_required
def updateImage() :
message=''
status=''
updateImageForm = UpdateImage()
if updateImageForm.validate_on_submit() :
id = request.json.get('id')
action = request.json.get('action')
image = request.json.get('image')
presentaion = Presentaions.query.filter_by(deleted=1,id=id).first()
if presentaion ==None :
return jsonify({'status':'apperror','message': 'Pressentaion Not Found ..'})
presentaion.image = uploadMainPresntaionImage(image,id)
presentaion.last_updated_at = datetime.datetime.now()
presentaion.last_updated_by = current_user.id
db.session.commit()
return jsonify({'status': "success", 'message': 'Password Changed Successfuly'})
else:
errors = {}
for field, field_errors in updateImageForm.errors.items():
errors[field] = [str(error) for error in field_errors]
return jsonify({'status': "errors ", 'message': errors})
my js code is :
//get id for presentaion
$(".table_for_data").on( 'click', '.img-edit', function () {
id=$(this).attr('data-id');
$("#imageId").val(id)
});
$("#updateimageform").submit(function(e){
e.preventDefault()
//var formData = $(this).serialize();
//var allData = formData + "&action=editPass";
var fileInput = document.getElementById('image');
var image = fileInput.files[0];
var formData = new FormData();
var myaction = 'updateImage'
formData.append('image', image);
formData.append('id', id);
formData.append('action', myaction);
console.log(formData)
$.ajax({
url: "{{ url_for('presentation.updateImage') }} ",
type:"POST",
data: JSON.stringify(formData),
contentType: 'application/json',
beforeSend:function(){
},
statusCode: {
404: function() {
alert( "page not found" );
},
},
success:function(valdata) {
if(valdata['status'] == "success")
{
$('#updateImageResult').html('');
$('#updateImageResult').html('<div class="alert alert-success" role="alert">' + valdata['message'] + '</div>');
$("#updateimageform")[0].reset();
setTimeout(function(){$('#update-img').modal('hide');}, 2000);
}else if (valdata['status'] == "apperror"){
$('#updateImageResult').html('<div class="alert alert-danger" role="alert">' + valdata['message'] + '</div>');
}else{
var errors = valdata['message'];
for (var field in errors) {
if (errors.hasOwnProperty(field)) {
var errorMessages = errors[field];
for (var i = 0; i < errorMessages.length; i++) {
$('#updateImageResult').html('<div class="alert alert-danger" role="alert">' + errorMessages[i] + '</div>');
}
}
}
// $("#updatePasswordResult").html(valdata['message']);
}
}
});
return false;
});