title: How to submit multipart form in Yii2?
body: <p>I have a problem with my form because it cant serialize the image file. So how can I submit a form that contains an image file input in Yii2 using ajax? 
  (Below you can see the active form and the js code.)</p>
  
  <pre><code>&lt;div class="cars-form"&gt;
  
  &lt;?php $form = ActiveForm::begin(['options'=&gt;['id'=&gt;$model-&gt;formName(),'enableAjaxValidation'=&gt;true,'enctype'=&gt;'multipart/form-data']]); ?&gt;
  
  &lt;?= $form-&gt;field($model, 'name')-&gt;textInput(['maxlength' =&gt; true]) ?&gt;
  
  &lt;?=$form-&gt;field($model, 'colour')-&gt;widget(ColorInput::classname(), ['options' =&gt; ['placeholder' =&gt; 'Select Color...'],]); ?&gt;
  
  &lt;?=$form-&gt;field($model, 'imageFile')-&gt;widget(FileInput::classname(), [
  'options' =&gt; ['accept' =&gt; 'image/*'],'pluginOptions' =&gt; [
          'previewFileType' =&gt; 'image',
          'showUpload' =&gt; false],]);?&gt;
  
  &lt;?= $form-&gt;field($model, 'price')-&gt;textInput() ?&gt;
  
  &lt;div class="form-group"&gt;
      &lt;?= Html::submitButton($model-&gt;isNewRecord ? 'Create' : 'Update', ['class' =&gt; $model-&gt;isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?&gt;
  &lt;/div&gt;
  
  &lt;?php ActiveForm::end(); ?&gt;
  
  &lt;/div&gt;
  
  
  &lt;?php 
  $script = &lt;&lt;&lt; JS
  
  $('form#{$model-&gt;formName()}').on('beforeSubmit',function(e)
      {var \$form =$(this);
      $.post(
      \$form.attr("action"),
      \$form.serializefiles()
      )
      .done(function(result) 
      {
      if (result == 1)
      {
        $(\$form).trigger("reset");
        $.pjax.reload({container:'#cars'});
      }
  
      else
      {
        $("#message").html(result);
      }
  
      }).fail(function(data)
      {console.log("server error: " + data);});
      return false;
  });
  
  JS;
  $this-&gt;registerJs($script);?&gt;
  </code></pre>
  
  <p>(Controller)</p>
  
  <pre><code>public function actionCreate()
  {
      $model = new Cars();
  
      if ($model-&gt;load(Yii::$app-&gt;request-&gt;post())) {
  
          $imageName= $model-&gt;name;
          $model-&gt;imageFile= UploadedFile::getInstance($model,'imageFile');
          $model-&gt;imageFile-&gt;saveAs('carsimages/'.$imageName.'.'.$model-&gt;imageFile-&gt;extension);
          $model-&gt;image='carsImages/'.$imageName.'.'.$model-&gt;imageFile-&gt;extension;
  
          if($model-&gt;save())
          //{
              //return $this-&gt;redirect(['view', 'id' =&gt; $model-&gt;id]);
          //}
          {
             echo 1;
          }
  
          else
          {
              echo 0;
          }                   
      }
  
      else {
      return $this-&gt;renderAjax('create', [
              'model' =&gt; $model,
      ]);
  }}
  </code></pre>