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>
-
1Maybe you can put the php value to a hidden input, and you can import it easily in javascript. :DMihálovics Rómeó– Mihálovics Rómeó2017年03月20日 09:37:36 +00:00Commented Mar 20, 2017 at 9:37
-
Possible duplicate of How to pass variables and data from PHP to JavaScript?wildeyes– wildeyes2017年03月20日 09:39:15 +00:00Commented Mar 20, 2017 at 9:39
-
1first 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 ;Edwin– Edwin2017年03月20日 09:39:56 +00:00Commented Mar 20, 2017 at 9:39
-
1put single quotes around php opening and closing tags in javascript. Thanks.user1544541– user15445412017年03月20日 09:46:20 +00:00Commented 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.Yeasir Arafat Majumder– Yeasir Arafat Majumder2017年03月20日 12:39:50 +00:00Commented Mar 20, 2017 at 12:39
2 Answers 2
Comments
Try in this way:
<? php
$dataSelected = $coreModel -> selectData('*','oc_attribute_group_description');
?>
<script>
var attrGroups = "<?php echo $dataSelected; ?>";
console.log(attrGroups);
</script>