I am trying to use FormData()
for sending texts and images. It's not working
$('#saveBtn').click(function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var formDataEdit = new FormData();
//formDataEdit.append('images', $('#images')[0].files[0]); // for single item
formDataEdit.append('nameForEdit', $("input[name='nameForEdit']")
.val());
formDataEdit.append('codeForEdit', $('#codeForEdit').val());
formDataEdit.append('categoriesForEdit', $('#categoriesForEdit').val());
formDataEdit.append('stokForEdit', $('#stokForEdit').val());
let TotalImages = $('#photoForEdit')[0].files.length; //Total Images
let images = $('#photoForEdit')[0];
for (let i = 0; i < TotalImages; i++) {
formDataEdit.append('images' + i, images.files[i]);
}
formDataEdit.append('TotalImages', TotalImages);
console.log(formDataEdit.get('nameForEdit')); // it's works, returning the value of name.
console.log(formDataEdit.append('codeForEdit', $('#codeForEdit')
.val())); // it's not working. Returning undefined. */
$.ajax({
url: "products/" + id,
method: 'PUT',
data: formDataEdit,
enctype: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
dataType: 'JSON',
async: true,
headers: {
'Content-Type': undefined,
},
xhr: function() {
myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(result) {
if (result.errors) {
$('.alert-danger').html('An error in your input fields');
$.each(result.errors, function(key, value) {
$('.alert-danger').show();
$('.alert-danger').append('<strong><li>' + value +
'</li></strong>');
});
} else {
$('.alert-danger').hide();
$('.alert-success').show();
$('.datatable').DataTable().ajax.reload();
setInterval(function() {
$('.alert-success').hide();
$('#ajaxModel').hide();
location.reload();
}, 2000);
}
},
error: function(response) {
$('#codeError').text(response.responseJSON.errors.code);
$('.alert-danger').html('An error in your input fields');
$.each(response.errors, function(key, value) {
$('.alert-danger').show();
$('.alert-danger').append('<strong><li>' + value +
'</li></strong>');
});
}
});
});
Everytime I use dd($request->get('stokForEdit'))
for example, it's returning null
But, when I change code to below without FormData()
, it's working.
url: "products/" + id,
method: 'PUT',
data: {
nameForEdit: $('#nameForEdit').val(),
codeForEdit: $('#codeForEdit').val(),
categoriesForEdit: $('#categoriesForEdit').val(),
stokForEdit: $('#stokForEdit').val(),
},
enctype: 'multipart/form-data',
cache: false,
//contentType: false,
//processData: false,
dataType: 'JSON',
async: true,
headers: {
'Content-Type': undefined,
},
xhr: function() {
myXhr = $.ajaxSettings.xhr();
return myXhr;
},
I can't use the second way, because I need to send an images. Help me with the soultion!
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire