S
S
shanik2017-09-29 11:45:10
Yii
shanik, 2017-09-29 11:45:10

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();
        });
    });


59ce02cb27a01745187963.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2017-09-29
@slo_nik

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))
  })
})

Well, then do it yourself, you will not have any difficulties with this.
PS
And, by the way, uploading files using ajax has nothing to do with yii2. Although on yii2, even on pure js + php, you need to use FormData ()

S
shanik, 2017-09-29
@shanik

formData.forEach(function(item, i, arr){
                console.log(item+' '+i+' '+arr);

returns this:
How to pull out the files themselves from there so that they fill the array normally:
[Foto] => Array
        (
            [file] => Array
                (
                    [0] => 
                )
        )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question