Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Guys!
I'm making an audio player using html and javascript.
I have problem with searching for music files.
I don't know how to get all files from dir /songs/ and put them into var songs.

I get this error wich says that variable songs is undefined:
exp-1.10-vPlayer.js:18 Uncaught TypeError: Cannot read property '0' of undefined
at playSong (exp-1.10-vPlayer.js:18)
at playOrPauseSong (exp-1.10-vPlayer.js:39)
at HTMLButtonElement.onclick ((index):13)


What I have tried:

My code:
PHP
echo '<script> var songs; </script>';
$spath = $_SERVER['DOCUMENT_ROOT'];
$spath .= "/vas/beta/audio-player/songs/";
$fileList = glob('{$spath}*.mp3');

foreach($fileList as $filename){
    echo '<script> songs.push("', $filename, '"); </script>';
}
Posted
Updated 19-Jul-20 11:48am
Comments
Richard MacCutchan 19-Jul-20 8:42am    
Which is line 18?
M3T3XU 19-Jul-20 13:53pm    
Line 18 is just call to songs:

function playSong(){

alert(songs[0]);
...
Richard MacCutchan 19-Jul-20 15:04pm    
Well variable songs is not defined at that point, so you need to trace back through the code to find out why.

1 solution

Ok.
I found out what was wrong. I corrected my php and js code and now it works perfect!
PHP
echo '<script>';
echo "\r\n";
echo 'var songs = [];';
echo "\r\n";
$spath = $_SERVER['DOCUMENT_ROOT'];
$spath .= "/vas/beta/audio-player/songs/";
$files = scandir($spath);
foreach($files as $file) {
   if($file != '.' && $file != '..'){
      echo 'songs.push("/vas/beta/audio-player/songs/', $file, '");';
      echo "\r\n";
   };
}

echo '</script>';
echo "\r\n";
 
Share this answer
 
Comments
Richard Deeming 20-Jul-20 6:57am    
You'll need to make sure you properly encode the $file to ensure that it doesn't escape the Javascript string context. Otherwise you could be opening up a potential cross-site scripting vulnerability in your code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900