English 中文(简体)
Yii Tutorial

Yii Useful Resources

Selected Reading

Yii - AJAX Validation
  • 时间:2024-09-17

Yii - AJAX Vapdation


Previous Page Next Page  

The username vapdation should only be done on the server side because only the server has the needed information. In this case, you can use AJAX-based vapdation.

Step 1 − To enable the AJAX vapdation, modify the registration view this way.

<?php
   use yiiootstrapActiveForm;
   use yiiootstrapHtml;
?>
  
<span class = "row">
   <span class = "col-lg-5">  
   
      <?php $form = ActiveForm::begin([ id  =>  registration-form , 
          enableAjaxVapdation  => true]); ?>  
      <?= $form->field($model,  username ) ?>  
      <?= $form->field($model,  password )->passwordInput() ?>  
      <?= $form->field($model,  email )->input( email ) ?>  
      <?= $form->field($model,  country ) ?>  
      <?= $form->field($model,  city ) ?>  
      <?= $form->field($model,  phone ) ?>  
      <span class = "form-group">             
         <?= Html::submitButton( Submit , [ class  =>  btn btn-primary , 
             name  =>  registration-button ]) ?>
      </span>
      
      <?php ActiveForm::end(); ?>  
   </span>
</span>

We should also prepare the server, so that it can handle the AJAX requests.

Step 2 − Modify the actionRegistration method of the SiteController this way.

pubpc function actionRegistration() { 
   $model = new RegistrationForm(); 
   if (Yii::$app->request->isAjax && $model->load(Yii::$app->request>post())) { 
      Yii::$app->response->format = Response::FORMAT_JSON; 
      return ActiveForm::vapdate($model); 
   } 
   return $this->render( registration , [ model  => $model]); 
}

Step 3 − Now, go to http://localhost:8080/index.php?r=site/registration, you will notice that the form vapdation is done by AJAX requests.

Ajax Requests Advertisements