I have a Laravel application and it has a form which submits its data using an Ajax call, submitted data is handled by a Laravel backend. All works fine for text data but I need to add a file upload to it, but when I'm trying to submit the data using the same code, it doesn't work.
This form is a Laravel component,
<form class="form-horizontal" action="@yield('content-form-action')" name="mfrm" id="mfrm" method="post" autocomplete="off" enctype="multipart/form-data">
Ajax call,
function saveData() {
var applicationId = $('#applicationId').val();
var jobReqId = $('#jobReqId').val();
var attachment = $('#atcb').val();
var prefix = $('#prefix').val();
var famName = $('#famname').val();
var nic = $('#nic').val();
var dataObject = {
applicationId: applicationId,
attachment: attachment,
jobReqId: jobReqId,
prefix: prefix,
famName: famName,
nic: nic,
}
$.ajax({
type: "POST",
url: applicationAttachingFormSubmitUrl,
async: false,
data: dataObject,
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
},
beforeSend: function () {
cursorWait();
add_panelLoader($('#application-insert-form'));
},
success: function (status) {
if (status.alert['type'] == "success") {
getApplicationData();
successAlert(status.alert['mssg'], status.alert['burl'], status.alert['rfms']);
} else if (status.alert['type'] == "danger") {
dangerAlert(status.alert['mssg'], status.alert['burl'], status.alert['rfms']);
} else if (status.alert['type'] == "info") {
infoAlert(status.alert['mssg'], status.alert['burl'], '');
} else if (status.alert['type'] == "warning") {
warningAlert(status.alert['mssg'], status.alert['burl'], '');
}
remove_panelLoader($('#application-insert-form'));
cursorDefault();
formclear();
},
error: function () {
remove_panelLoader($('#application-insert-form'));
cursorDefault();
},
}).fail(function (xhr, status, textStatus, error) {
located(xhr);
});
}
I have tried below way but not working. This is the way mentioned in other solutions and tutorials. If you need more details to get something clarified, I can update the code. TIA!
function saveData() {
$('mfrm').submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') },
url: applicationAttachingFormSubmitUrl,
data: formData,
type: 'post',
async: false,
processData: false,
contentType: false,
success:function(response){
console.log(response);
alert('uploaded');
},
error: function () {
console.log('error');
},
});
});
}