Yii2: Processing jQuery Ajax

This is skeleton code example on posting form data in JSON format processing by Yii’s controller action. Although this example uses Yii, the code can be easily adaped to pure PHP code.

The View

Assuming form with id the_form has already been included in a view file. At the end of the file add the following JavaScript / jQuery code:

$js = <<< 'SCRIPT'
$('#the_form').submit(function() { 
        url: '/controller/ajax', 
        type: 'post', 
        data: $(this).serialize(), 
        success: function(data) { 
$this->registerJs($js, static::POS_END);


  • Line 5: type – GET (default) or POST
  • Line 6: data. If type = GET, this is GET request appended to the end of URL.
  • Line 8: processing data returned from PHP action in next section. To access specific key in data array, eg data.key.

The Action

In controller file:

public function actionAjax() {
    Yii::$app->response->format = Response::FORMAT_JSON;
    $post = Yii:: $app->request->post();
    $data = [];
    if (Yii::$app->request->isAjax) {
        // do your data processing here

        // set response data
        if (success) {
            $data = ['sucess' => true, /* rest of the data */];
        else {
            $data = ['success' => false, 'error' => 'Some error message'];
        return $data;


  • Line 3: data posted via line 6 in above view file.
  • Line 5: make sure this is Ajax request.
  • Line 10: set successful response, indicated by ‘success’ key in this example. Array key will be accessed by line 8 in above view file.
  • Line 13: set error response.


Leave a Reply

Your email address will not be published. Required fields are marked *