I have a playlist script in my wordpress theme that puts the URL from a file in the media gallery into a playlist script that can be read by the audio player.
<script type="text/javascript">
var myPlaylist = [
<?php
foreach ($audiofiles as $file)
{
echo "{
mp3:'".$file->guid."',
title:'".$file->post_title."',
artist:'"."',
rating:5,
buy:'".$file->post_excerpt."',
price:'"."',
duration:'"."',
cover:'"."'
},"
; }
?>
];
</script>
My problem is that I need to figure out how to change the output of the php script on the LAST item, so that there is no comma after the "}". I've been told this is an AJAX problem, but I'm not sure where to begin.
When passing objects from PHP to JS, the safest, simplest way is to use json_encode
. This way you won't have to worry about breaking your JS syntax in case $file->post_title
contains '
or any other character that would break it.
<?php
$playlist = array();
foreach ($audiofiles as $file)
{
$playlist[] = array(
'mp3'=>$file->guid,
'title'=>$file->post_title,
'artist'=>'',
'rating'=>5,
'buy'=>$file->post_excerpt,
'price'=>'',
'duration'=>'',
'cover'=>''
);
}
?>
<script type="text/javascript">
var myPlaylist = <?= json_encode($playlist) ?>;
</script>
Try the following one:
<?php
$playlist = array();
foreach ($audiofiles as $file)
{
$playlist[] = "{
mp3:'".$file->guid."',
title:'".$file->post_title."',
artist:'"."',
rating:5,
buy:'".$file->post_excerpt."',
price:'"."',
duration:'"."',
cover:'"."'
}";
}
?>
<script type="text/javascript">
var myPlaylist = [
<?php echo implode(',' $playlist);?>
];
</script>
Assuming that $audiofiles
is associative array, have you tried this:
<?php
$totalFiles = count($audiofiless);
$i = 0;
foreach ($audiofiles as $file)
{
echo "{
mp3:'".$file->guid."',
title:'".$file->post_title."',
artist:'"."',
rating:5,
buy:'".$file->post_excerpt."',
price:'"."',
duration:'"."',
cover:'"."'
}" . (++$i < $totalFiles ? ',' : '');
; }
?>
However, if it's not an associative then it even simplier since you don't have to increment anything and you can use ordinary for
cycle...
You could change the foreach to a for and do something like this:
<script type="text/javascript">
var myPlaylist = [
<?php
for ($i=0; $i<=$audiofile.length; $i++)
{
$file = $audiofile[$i];
echo "{
mp3:'".$file->guid."',
title:'".$file->post_title."',
artist:'"."',
rating:5,
buy:'".$file->post_excerpt."',
price:'"."',
duration:'"."',
cover:'"."'
}"
if ($i<$audiofile.length)
{
echo ","
}
; }
?>
];
</script>