Learn how to use AJAX in yii framework

this tutorial is part of reservation series

Yii2 provides appropriate attributes for some widgets to make AJAX calls; sometimes, however, writing a JavaScript code in these attributes will make code hard to read, especially if we are dealing with complex codes.

Consequently, to make an AJAX call, we will use external JavaScript code executed by registerJs().

This is a template of the AJAX class using the GET or POST method:

$this->registerJs( <<< EOT_JS
     // using GET method
  url: url,
  data: data,
  success: success,
  dataType: dataType

     // using POST method
  url: url,
  data: data,
  success: success,
  dataType: dataType


An AJAX call is usually the effect of a user interface event (such as a click on a button, a link, and so on). So, most of the time an AJAX call is directly connected to the .on() event of jQuery on the HTML elements (anchors, buttons, and so on). For this reason, it is important to remember how Yii2 renders the name and id attributes of input fields.

When we call Html::activeTextInput($model, $attribute) or in the same way use <?= $form->field($model, $attribute)->textInput() ?>.

The name and id attributes of the input text field will be rendered as follows:

  • id : The model class name separated with a dash by the attribute name in lowercase; for example, if the model class name is Room and the attribute is floor, the id attribute will be room-floor
  • name: The model class name that encloses the attribute name, for example, if the model class name is Reservation and the attribute is price_per_day, the name attribute will be Reservation[price_per_day]; so every field owned by the Reservation model will be enclosed all in a single array

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest