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>
6
  • 1
    Maybe you can put the php value to a hidden input, and you can import it easily in javascript. :D Commented Mar 20, 2017 at 9:37
  • Possible duplicate of How to pass variables and data from PHP to JavaScript? Commented Mar 20, 2017 at 9:39
  • 1
    first try a var_dump($dataSelected) in php. If all is alright, maybe try var attrGroups = '<?php echo json_encode($dataSelected);?>'; or just without the ' but with the extra ; Commented Mar 20, 2017 at 9:39
  • 1
    put single quotes around php opening and closing tags in javascript. Thanks. Commented Mar 20, 2017 at 9:46
  • @MihálovicsRómeó: that's a tricky alternative solution. Thanks. But I would first try to achieve what I explained in the question. Commented Mar 20, 2017 at 12:39

2 Answers 2

1

As suggested in: previous comment

try:

var attrGroups = '<?php echo json_encode($dataSelected);?>';
Sign up to request clarification or add additional context in comments.

Comments

1

Try in this way:

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

<script>
 var attrGroups = "<?php echo $dataSelected; ?>";
 console.log(attrGroups);
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.