'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,
    ],


Solution 1:[1]

You can use

Url::toRoute

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

Solution 2:[2]

Can you use Url helper class, it will change your url based on url rules which is configured in web.php file.

$.ajax({ 
   //use Url helper class for ajax url 
   url: "<?= yii\helpers\Url::to(['@web/checks/items'],true) ?>", 
   type: 'get', 
   data: { 
     category:category, 
     _csrf : "<?=Yii::$app->request->getCsrfToken()?>" 
   }, 
   success: function (data) { 
     var parsedResult = $.parseJSON(data); 
     ..... 
     $("#labels_trackcenter").html(html); 
   } 
});

Solution 3:[3]

incase of External Js

Specify Url in the form

<form action="<?php echo Url::toRoute('participant-prod/pull-live-data'); ?>" method="get" id="pull-part-data-form">

Call Url in the JS file

$("#pull-part-data-form").submit((e) => {
e.preventDefault();
let targetUrl = $("#pull-part-data-form").attr('action');
$.ajax({
    url: targetUrl,
    method: 'get',
    data: $("#pull-part-data-form").serializeArray(),
    success: function (response) {
        
    },
    error: function (error) {
        console.error(error)
    }
});

})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 G. Mansour
Solution 2
Solution 3 Wainaina Nik