1

My file is with .php extension. I have a php variable $dataSelected that is an associative array. Actually it's the result set of a select query output. Here is what this variable has when printing with print_r:

Array
(
 [0] => Array
    (
        [attribute_group_id] => 3
        [language_id] => 1
        [name] => Memory
    )

 [1] => Array
    (
        [attribute_group_id] => 4
        [language_id] => 1
        [name] => Technical
    )

 [2] => Array
    (
        [attribute_group_id] => 5
        [language_id] => 1
        [name] => Motherboard
    )

 [3] => Array
    (
        [attribute_group_id] => 6
        [language_id] => 1
        [name] => Processor
    )

)

I want to access this variable from within my javascript code snippet(on the same page). My goal is to use the result of the query(which is stored in the $dataSelected variable) to dynamically add option element to a select tag.

I have tried the below code. But it is printing null in the console. Can anyone please help what I am doing wrong here?

<? php
    $dataSelected = $coreModel -> selectData('*','oc_attribute_group_description');
?>

<script>
 var attrGroups = <?php echo json_encode($dataSelected)?>;
 console.log(attrGroups);
</script>
Yeasir Arafat Majumder
  • 1,222
  • 2
  • 15
  • 34

2 Answers2

1

Try in this way:

<? php
    $dataSelected = $coreModel -> selectData('*','oc_attribute_group_description');
?>

<script>
 var attrGroups = "<?php echo $dataSelected; ?>";
 console.log(attrGroups);
</script>
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32
1

As suggested in: previous comment

try:

var attrGroups = '<?php echo json_encode($dataSelected);?>';
Community
  • 1
  • 1
Edwin
  • 2,146
  • 20
  • 26