I want to upload file using Ajax in yii2 framework this is my code, but in controller "get Instance" return null because of serialize data; how can i do this?
This is my controller:
<?php
public function actionUpdate($id)
{
$model = Signature::findOne([
'user_id' => $id,
]);
if ($model->load(Yii::$app->request->post())) {
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/signature/' . $model->user_id . '.' . $model->file->extension);
$model->url = 'uploads/signature/' . $model->user_id . '.' . $model->file->extension;
if ($model->save()) {
echo 1;
} else {
echo 0;
echo $model->file;
}
} else {
return $this->renderAjax('update', [
'model' => $model,
]);
}
}
?>
This is my script code I can't get my file in controller and it return null
<?php $script = <<<JS
$('form#{$model->formName()}').on('beforeSubmit', function(e)
{
var \$form = $(this);
$.post(
\$form.attr("action"),
\$form.serialize(),
)
.done(function(result){
if(result == 1)
{
$(document).find('#update_signature_modal').modal('hide');
$.pjax.reload({container:'#branchesGrid'});
//alert();
} else {
alert(result);
}
}).fail(function()
{
console.log("server error");
});
return false;
});
JS;
$this->registerJs($script);
?>