tklustig
tklustig

Reputation: 503

How to define $.get url using enablePrettyUrl=>true

Following code will do its job as intended, if enablePrettyUrl will be set to false:

<?php
$script = <<< JS
   $('#zip_code').change(function(){
       var zipId=$(this).val();
       $.get('index.php?r=locations/get-city-province',{zipId:zipId},function(data){
       var data=$.parseJSON(data);
       alert(data.city+" liegt in "+data.province+"! Die Id ist "+zipId);
       $('#customers-city').attr('value',data.city);
       $('#customers-province').attr('value',data.province);
   });
});

JS;
$this->registerJS($script);
?>

Following code won't, if enablePrettyUrl will be set true:

 $.get('locations/get-city-province',{zipId:zipId},function(data){

Here are rules of UrlManager:

'urlManager' => [
    'class' => 'yii\web\UrlManager',
    'enablePrettyUrl' => true,
    'showScriptName' => true,
    'enableStrictParsing' => true,
    'rules' => [
        'locations' => 'locations/index',
        'locations_create' => 'locations/create',
        'locations_delete' => 'locations/delete',
        'locations_update' => 'locations/update',
        'locations_SaveAsNew' => 'locations/save-as-new',
        'locations_pdf' => 'locations/pdf',
        'locations_view' => 'locations/view',
        // ...
    ],
],

Any ideas, how to code $.get in correct way? Here is method of Controller:

public function actionGetCityProvince($zipId) {
    $location = Locations::findOne($zipId);
    echo Json::encode($location);
}

Upvotes: 0

Views: 41

Answers (1)

Insane Skull
Insane Skull

Reputation: 9358

Use Url::to() or Url::toRoute()

<?php
$url = yii\helpers\Url::to(['locations/get-city-province']);
$script = <<< JS
    $('#zip_code').change(function(){
        var zipId = $(this).val();
        $.get('$url', {zipId:zipId}, function(data){
            var data = $.parseJSON(data);
            alert(data.city+" liegt in "+data.province+"! Die Id ist "+zipId);
            $('#customers-city').attr('value',data.city);
            $('#customers-province').attr('value',data.province);
        });
   });
JS;
$this->registerJS($script);
?>

Upvotes: 1

Related Questions