-2

I am newbie to Yii. I have a set of array values in a variable in php. I use these elements to accommodate in auto-complete using JavaScript. I don't know how to pass these array values to JavaScript so that it gives me the required result.

My controller action:

public function actionIndex()
    {

            $user = Yii::app()->db->createCommand()
    ->select('cust_name')
    ->from('mst_customers')
    ->queryAll();

       $dataProvider=new CActiveDataProvider('model_name');

                $this->render('index',array(
            'dataProvider'=>$dataProvider,


        ));

    }

My view:

<!--Content-->

<div id="content">
    <div style="padding: 10px;">
        <a href="<?php echo $this->createUrl('/Nimsoft/create');?>" title="Create New Host" class="btn btn-primary circle_ok" style="text-decoration: none;" >Add New Host to Customer</a>

    <div style="float:right">
                         <?php
                            echo CHtml::link('Upload Customer CSV', array('/Controller/uploadCustomers'), array(
                            'onclick'=>'return hs.htmlExpand(this, { objectType: "iframe", wrapperClassName: "full-size", align: "center" } )',
                            'class'=>'btn btn-primary',
                            'id'=>'upload_link',
                            ));
                         ?>                          
                     </div>
    </div>
    <h3><?php echo $title; ?></h3>


    <div class="innerLR">
        <div class="row-fluid">
<?php 
echo $user=$_GET['user'];
$obj=$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,

    //'afterAjaxUpdate'=>'\'changeTRColor()\'',
    //'itemView'=>'_view',
    'columns'=>array(

                array(            // display 'create_time' using an expression
                            'name'=>'name',
                                            'value'=>'$data->host_name',
                ),
                array(
                            'name'=>'serviceId',
                            'value'=>'$data->host_serviceid',
                ),

                array(
                                            'name'=>'customer',
                                            'value'=>'$data->customers->cust_name',
                ),
                array(
                                    'class'=>'CButtonColumn',
                                    'template'=>'{delete}{update}',)



),
)); 

?>

       </div>

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script type="text/javascript">
   $(document).ready(function () {
       $('#Search').keyup(function () {

$.fn.yiiGridView.update('id of your grid to be updated', {
        data: $(this).serialize()
    });
});
   });

  //autocomplete
  $(function() {
    var availableTags = [
        <?php echo json_encode($user);?>

      /*"ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"*/
    ];
    $( "#Search" ).autocomplete({
      source: availableTags
    });
  });
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="Search">Search Customer: </label>
  <input id="Search">
</div>


</body>
</html>

        <div class="separator bottom"></div>
    </div>
</div>
<!-- // Content END -->
<div class="clearfix"></div>
<!-- // Sidebar menu & content wrapper END -->

<div id="footer" class="hidden-print">
<?php $this->renderPartial('application.views.layouts._footer_inc');  ?>
</div>

Please help me do this. Thanks in advance.

Thein Hla Maw
  • 685
  • 1
  • 9
  • 28
user3107044
  • 21
  • 2
  • 10

2 Answers2

1

or you can use Yiis CJSON::encode()

<script>
   var myVariables = <?php echo CJSON::encode($user); ?>; // forgot to close with semicolon
</script>
Developerium
  • 7,155
  • 5
  • 36
  • 56
0

You're doing it right by using json_encode(). However, if what you have is already an array, don't wrap it in another array. Instead of this:

var availableTags = [
    <?php echo json_encode($user);?>
];

Just do this:

var availableTags = <?php echo json_encode($user); ?>;

Also, be aware that you have likely opened yourself up to XSS attacks, and are at least at risk of creating some invalid HTML. Any time you need to put arbitrary data into the context of HTML, you must escape it. Instead of this:

<h3><?php echo $title; ?></h3>

Do this:

<h3><?php echo htmlspecialchars($title); ?></h3>

Better yet would be to use a template engine.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • I did a alert() of the javascript variable but it returns an alert"null" – user3107044 Feb 17 '14 at 05:16
  • @user3107044 Did you try to debug the problem? I have no idea what's in your variables. What does `var_dump($user)` get you? I bet it will be `null` or similar. – Brad Feb 17 '14 at 05:17
  • yes, the array values from my controller is not passed to the view. what is the remedy for this, I am asking this since i am a starter in yii – user3107044 Feb 17 '14 at 05:23
  • @user3107044 You asked how to pass a variable to JavaScript... not how to handle your user object in Yii. You should post a separate question for that. – Brad Feb 17 '14 at 06:04
  • your render function must be $this->render('index',array( 'dataProvider'=>$dataProvider, 'user'=>$user )); – Rahul Thakur Feb 17 '14 at 08:17