Answer the question
In order to leave comments, you need to log in
Why are files not being sent via AJAX Yii2?
<?php $f = ActiveForm::begin(['id' => 'flora', 'action' => $flora->isNewRecord ? Url::base(true) . '/create-flora/add' : Yii::$app->request->url, 'options' => ['enctype' => 'multipart/form-data']]); ?>
...
<?= $f->field($foto, 'file[]')->fileInput(['multiple' => true, 'class' => 'btn btn-success'])->label('Добавить фотографии'); ?>
<?= Html::submitButton($flora->isNewRecord ? 'Добавить флору' : 'Изменить флору', ['id' => 'addFlora', 'class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
$(function () {
$('#addFlora').click(function (e) {
var $form = $('#flora');
var formData = new FormData($form[0]);
var id_taxon = 0;
if ($('.table-striped > tbody > tr input:radio').is(':checked')) {
id_taxon = $('.table-striped > tbody > tr input:radio').attr('data-key');
}
/* var file_data = $('#foto-file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
console.log(file_data);*/
/* $.each($('#foto-file')[0].files, function(i, file) {
formData.append('Foto[file][]', file);
}); */
formData.append('Flora[taxon_id]',id_taxon);
$.ajax({
processData: false, // Important!
contentType: false,
cache: false,
type: $form.attr('method'),
url: $form.attr('action'),
data: formData
}).done(function (data) {
console.log(data);
}).fail(function () {
console.log('fail');
});
//отмена действия по умолчанию для кнопки submit
e.preventDefault();
});
});
Answer the question
In order to leave comments, you need to log in
Good afternoon.
And why did you decide that they will be sent via ajax?
For this to happen, a completely different approach is needed.
Use the FormData() class and you'll be fine.
Here is a small example:
$(function(){
function Testing(url, form){
var file = '';
var formdata = new FormData(form[0]);
formdata.forEach(function(item, i, arr){
if(i == 'files'){
formdata.append(item.name, item)
}
})
$.ajax({
url: url,
type: 'POST',
processData: false,
contentType: false,
data: formdata,
success: function(data){
console.log(data)
}
})
}
$('#form-data').on('submit', function(e){
e.preventDefault();
Testing('upload.php', $(this))
})
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question