I'm trying to create an object in javascript with PHP. This is my script:
<script>
$(document).ready(function(){
var genres = [
<?php
$last = count($userGenres) - 1;
$i = 0;
foreach($userGenres as $a){
$i++;
echo '{"value":"'.$a['genre'].'", "name":"'.$a['name'].'"}';
if($i < $last){
echo ',';
}
}
?>
];
});
</script>
When I check the generated source, it creates a valid object, but the whole script in that tag doesn't work now. How would fix this, without JSON?
Thanks
It's just a regular HTML <script> tag that calls a PHP file instead of a JavaScript file. But there's one catch: In that PHP file, you still have to use JavaScript.
Besides, PHP and JavaScript similarities, these two languages are a powerful combination when used together. Large numbers of websites combine PHP and JavaScript – JavaScript for front-end and PHP for back-end as they offer much community support, various libraries, as well as a vast codebase of frameworks.
PHP syntax is applicable only within PHP tags. PHP can be embedded in HTML and placed anywhere in the document. When PHP is embedded in HTML documents and PHP parses this document it interpreted the section enclosed with an opening tag (<? php) and closing tag (?>) of PHP and ignore the rest parts of the document.
You forgot to close the .ready()
method and the anonymous function inside of it.
Try this:
<script>
$(document).ready(function(){
var genres = [
<?php
$last = count($userGenres) - 1;
$i = 0;
foreach($userGenres as $a)
{
$i++;
echo '{"value":"'.$a['genre'].'", "name":"'.$a['name'].'"}';
if($i < $last)
{
echo ',';
}
}
?>
];
});
</script>
As the comment says you should consider using (php function)json_encode instead, which will turn...
php:
$a = array(
array("gender"=> "male", "name"=> "Bob"),
array("gender"=> "female", "name"=> "Annie")
);
Into json:
[
{gender:"male", name:"Bob"},
{gender:"female", name:"Annie"}
]
Echoing json_encode($a) would output it just like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With