My form is set with method=post and enctype="multipart/form-data" with regular submitting form information and photo were updated but when I want to use the Ajax ,everything have been inserted but not my photo!! What is the solution ?
$("#course-frm").submit(function(event){
event.preventDefault();
var formID = 'course-frm';
var form = $("#"+formID+'-container'+" form");
const formData = new FormData(this);
$.ajax({
url: event.target.action,
type: event.target.method,
data: formData,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (data) {
if(data == 'success'){
sweetAlertShow('عملیات ثبت با موفقیت انجام شد', 'The operation was Successful', 'success');
form.trigger('reset');
$("#course-frm-container").load(" #course-frm-container");
}else if(data == 'unsuccess'){
sweetAlertShow('امکان ثبت وجود ندارد', 'The operation was Unsuccessful', 'error');
}
},
error: function(xhr){
var data = xhr.responseJSON;
if($.isEmptyObject(data.errors) == false) {
$.each(data.errors, function (key, value) {
$('#'+formID +'-'+ key)
.closest('.form-group')
.addClass('has-error')
.append('<span class="help-block">' + value + '</span>');
});
}
}
});
});
You need to create a form data object. In the ajax function, set processData
to `false.
Because data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
JS
$("form").submit(function(evt){
evt.preventDefault(); //prevent refresh
const formData = new FormData(this); // you need to create a FormData obj to be able to send files
$.ajax({
url: 'upload-my-files', //change this to your url
type: 'POST',
data: formData, //put formData as body data
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (data) {
console.log(data);
}
});
});
References:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.