Overcoming removal of ajaxlink & client helpers in Yii 2.0

With Yii Framework 2.0, one of the many changes, that Yii 1.x developers will face is removal of all client helpers and revamp of the CClientScript functionality. For example no more CHtml::ajaxLink or Html::ajaxLink. How do you cater to such requirements in Yii 2.0?

Reasoning

One of the critical changes in Yii 2 framework design that you will notice versus Yii 1.x, is that Yii 2 focuses on moving the entire presentational layer to a new View object. With this change, the Yii 2 team has also eliminated most of the client related functionality embedded in PHP classes from the core framework. Thus it has made the code cleaner to use. Hence, helpers like ajaxLink are no more available. This helps you manage your client assets better, improves performance, and control them better.

Solution

You can easily create and combine all such client helpers into separate JS files, based on your need. Use the new AssetBundle and AssetManager functionality with the View object in Yii2, to manage these assets and how they are loaded.

Alternatively, inline assets (JS/CSS) can be registered at runtime from within the View.
For example you can clearly simulate the ajaxLink feature using an inline javascript as shown below. It is however recommended you merge client code (JS/CSS) into separate JS/CSS files. You can load these JS files in your view or view layout through the AssetBundle. Note there is no more need of a CClientScript anymore.

$script = <<< JS
$('#el').on('click', function(e) {
    $.ajax({
       url: '/path/to/action',
       data: {id: '<id>', 'other': '<other>'},
       success: function(data) {
           // process data
       }
    });
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default), 
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END