GEOFFREY MWANGI GEOFFREY MWANGI - 1 month ago 14
Ajax Question

Defining the url in yii ajax get

Am trying to perform an ajax get to a yii2 controller but the link fails to pass correctly

This is what i have tried:

$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. "/checks/items" ?>', //this fails
type: 'get',
data: {
category:category,
_csrf : '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function (data) {
var parsedResult = $.parseJSON(data);
.....
$("#labels_trackcenter").html(html);
}
});


How do i pass that url

These are the config url rules:

'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
],

Answer

You can try this,take care of concatenation.

       $this->registerJs("
        $.ajax({
        url: '" . yii\helpers\Url::to(["/checks/items"]) . "',
        //OR
        url: '" . Yii::$app->urlManager->baseUrl."/checks/items',

        type: get,
        data: {
                  category:category,
                  _csrf : '" . Yii::$app->request->getCsrfToken() . "'
              },
        success: function (data) {
                     var parsedResult = $.parseJSON(data);
                      .....
                     $("#labels_trackcenter").html(html);
        }
      });
   ");