Hi guys,
I’ve tried converting PHP array into JavaScript array.
<?php
//Get all data category from database.
$result = $this->classes_mdl->get_classes_name2();
//convert PHP array to JS array.
echo "<script>"
. "var classnames = " . json_encode($result) . ";"
. "</script>";
?>
<script>
//print values for testing only
document.write(classnames);
</script>
and the result was,
[object Object],[object Object],[object Object],[object Object]
So what was my mistake?
Try using console.log() instead of document.write . The objects are there, but document.write isn’t good at showing them.
@Jeff_Mott ;
I’ve changed the codes a little,
<?php
//Get all data category from database.
$result = $this->classes_mdl->get_classes_name2();
//convert PHP array to JS array.
$js_array = json_encode($result);
?>
<script>
//Converting to JS array.
var classnames = <?php echo $js_array; ?>;
//print classnames variable.
console.log(classnames);
</script>
And it works and the result was this,
[Object { nameclass="chemistry"},
Object { nameclass="class1"},
Object { nameclass="class2"},
Object { nameclass="Physics"}]
Now how do I convert classnames array above into this array example below,
var classnames = [
"chemistry",
"class1",
"class2",
"Physics"
];
Thanks in advance.
solidcodes:
Now how do I convert classnames array above into this array example below,
var classnames = [
"chemistry",
"class1",
"class2",
"Physics"
];
Thanks in advance.
Or change how your JavaScript writes it
for (item in classnames)
{
console.log(item.nameclass);
}
@cpradio ;
Thanks for the hint dude.
I already figured it out.
//Converting to JS array.
var classnames = <?php echo $js_array; ?>;
var x;
var availableTags = [];
for (x in classnames) {
//console.log(classnames[x].nameclass);
availableTags[x] = classnames[x].nameclass;
}
Problem solved.
Are you going to be using that classnames
variable elsewhere? If not, you could get PHP to spit out a JSON array of the names for you.
@Salathe ;
Can you show me the sample codes.
Thanks in advance.