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

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?


code from action 

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

        $model = new UploadForm();

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


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



            if ($model->validate()) {

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




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



use yii\widgets\ActiveForm;

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

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


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

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



            $(document).ready(function() {

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


                        url: 'path/to/'',

                        type: 'POST',

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

                        dataType: 'json',

                        success: function(data) {








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

1 Like

Fantastic! It works. Thank u)