Add jquery in Yii 2.0
Solution 1
Solved! I forgot to put the view methods in my view file: ($this->beginBody()
and so on)
Solution 2
You use the right way of registering jquery I suppose. But also base Yii 2.0 view class automatically register jquery if you register at least one js with position = POS_READY, for example (inside the view):
$this->registerJs($js, \yii\base\View::POS_READY);
or inside any controller or widget:
$this->getView()->registerJs($js, \yii\base\View::POS_READY);
so if you use any javascript code or file (you use it, beacause of you need jquery) you can get rid of that JqueryAsset at all.
Solution 3
If you want to include a js file from controller you may also use this
public function actionIndex() {
$this->getView()->registerJsFile('js/fileinput.js');
return $this->render('index', [
'model' => $model,
]);
}
Please view this link if you want more detail
http://www.yiiframework.com/doc-2.0/guide-output-client-scripts.html
![davey](https://i.stack.imgur.com/gfT1j.jpg?s=256&g=1)
davey
Updated on September 15, 2022Comments
-
davey almost 2 years
How can i add jQuery to my page in Yii 2.0?
In Yii 1.x you could just use:
Yii::app()->clientScript->registerCoreScript('jquery');
I already tried to override the View class with my own and tried to register jQuery there, but it doesn't shows up in my html page:
namespace frontend\components; /** * This is the base view object, it extends the yii\web\View so you can add custom view stuff here. */ class BaseView extends \yii\web\View { public function init() { parent::init(); \yii\web\JqueryAsset::register($this); } }
-
davey over 10 yearsYes, thanks! It worked this way, see my answer ;-) i forgot to put the view methods in my view.
-
Kshitiz about 10 yearsThis is in layout main.php file?
-
d.raev over 9 yearsIt should be
\yii\web\View::POS_READY
. (may be they changed it in the alpha update?)