0

In the below script default values are used. I would like to use values from database like <?php $user->location ?> i.e., I want to use users loaction data inside var states.

How do I do it?

 <script>
    $(document).ready(function() {
        var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California'
  ];
</script>
Amit Verma
  • 40,709
  • 21
  • 93
  • 115
Bloodhound
  • 2,906
  • 11
  • 37
  • 71

4 Answers4

2

Do like this

 <script>
     var test = "<?php json_encode($variable); ?>";
 </script>
Gustaf Gunér
  • 2,272
  • 4
  • 17
  • 23
2

In Yii you can use registerJS in your view file:

<?php
    $js = "var states = ['" . 
          implode("','", ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California']) .
          "'];";
    $this->registerJs($js, View::POS_BEGIN)

    // Now states is globally available in JS
?>
<div> ... your view html ... </div>

You can also add this JS code within a controller action instead of placing it into the view file:

public function actionIndex() {
    $js = "var states = ['" . 
          implode("','", ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California']) .
          "'];";

    $this->view->registerJs($js, View::POS_BEGIN);
    return $this->render('index', []);
}

Of course you can replace the array with any array you want. You could use e.g.:

$states = States::find()->column();
robsch
  • 9,358
  • 9
  • 63
  • 104
1

Try this:

<script type="text/javascript">
$(document).ready(function() {
    var states = <?php echo json_encode($user->location); ?>;
});
</script>
RuubW
  • 556
  • 4
  • 17
1
<?php
    $ar = array('one', 'two', 1, false, null, true, 2 + 5);
 ?>

<script type="text/javascript">
  var ar = <?php echo json_encode($ar) ?>;
  // ["one","two",1,false,null,true,7];
  // access 4th element in array
  alert( ar[3] ); // false
</script>

Thank You!!

Ragu Natarajan
  • 709
  • 3
  • 16