File upload by ajax

Hi. I try to upload file by ajax. For uploading files use example form documentation. I use ajax for serialize from and send data on server, but data which send by submit and ajax are different. Maybe someone knows how to do it?

You could try http://www.dropzonejs.com/

Thanks. But I have problem with data from ajax. When I send by submit button I getting img in model, but when I send it by ajax img is null. What do I do wrong?




<?php


code from action 


Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/images/';

        $model = new UploadForm();

        if (Yii::$app->request->isPost) {

            $model->load(Yii::$app->request->post());

            $model->file = UploadedFile::getInstance($model, 'file');

            var_dump($model);

            die();

            if ($model->validate()) {

                $model->file->saveAs(Yii::$app->params['uploadPath'] . $model->file->baseName . '.' . $model->file->extension);

                

            }

        }


        return $this->render('upload', ['model' => $model]);

        

   <?php

use yii\widgets\ActiveForm;


$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>


<?= $form->field($model, 'file')->fileInput() ?>


    <button>Submit</button>


<?php ActiveForm::end(); ?>




<button class="js-add-image">Add</button>

<?php

        $this->registerJs("

            $(document).ready(function() {

                $('.js-add-image').on('click', function() {

                    $.ajax({

                        url: 'path/to/'',

                        type: 'POST',

                        data: $('form').serialize(),

                        dataType: 'json',

                        success: function(data) {

                            console.log(data);

                        }

                    });

                });

            });

        ");

?>



This looks like a jquery question, rather than a YII question, this looks interesting:

http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/

1 Like

Fantastic! It works. Thank u)