I have an activeform using Ajax POST and the form fields are being sent, however it seems the file data is not. Here is the logically relevant code snippets from my files, underneath them is commentary on the test using a JS alert and the result
ActiveForm:
<?= $form->field($model, 'userphoto')->fileInput() ?>
Ajax Submit:
$script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit', function(event)
{
event.preventDefault();
var form = $(this);
formdata = new FormData(form[0]);
$.ajax({
url : form.attr('action'),
data : formdata,
cache : false,
contentType : false,
processData : false,
type : 'POST',
success: function (response)
{
alert(JSON.stringify(response.status);
$.pjax.reload({container:'#usergrid'});
$(form).trigger('reset');
},
});
return false;
});
JS;
$this->registerJs($script);
?>
Model:
use yii\web\UploadedFile;
class Usermanager extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'user';
}
public $userphoto;
public function rules()
{
return [
[['userphoto'], 'file', 'extensions' => 'jpg, png, gif',
'skipOnEmpty' => true],
Controller:
namespace app\controllers;
use Yii;
use app\models\Usermanager;
use yii\web\Controller;
use yii\web\Response;
use yii\web\UploadedFile;
class UsermanagerController extends Controller
{
public function actionCreate()
{
$model = new Usermanager();
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && Yii::$app->request->enableCsrfValidation)
{
Yii::$app->response->format = 'json';
$userphoto = UploadedFile::getInstance($model, 'userphoto');
/* return ['status' => $userphoto]; */
$model->photo = "web/". $model->username. "." .$userphoto->extension;
if($model->password !==''){
$model->password = Yii::$app->security->generatePasswordHash($model->password);
}
if($model->validate())
{
$model->save();
}
else
{
return ActiveForm::validate($model);
}
}
return $this->renderAjax('create', [
'model' => $model
]);
}
Here is the JS alert test result:
The test - (controller receives POST)
$userphoto = UploadedFile::getInstance($model, 'userphoto');
return ['status' => $userphoto];
The test result -> alert(JSON.stringify(response.status)):
{"name":"kde.jpg","tempName":"/tmp/phpjp3i4d",
"type":"image/jpeg","size":51253,"error":0}
As you can see the alert details the file attributes as if the file was received. However if an attempt is made to source the file extension thus:
$model->photo = "web/". $model->username. "." .$userphoto->extension;
The extension cannot be found. Further I have also tried to save with $userphoto->saveAs, however the console.log reports could not save null().
So does anyone have a successfully integrated AJAX Submit with file upload using YII2 that is maybe not using a Kartik widget ?