I've made an array that has all the file names in a certain directory. I've tested it and printed it to the screen. I want to use that array in javascript code, print it's members to the screen as well for a php for loop.

<!DOCTYPE html>
<html>
<head>
<body>

<?php
$i=0;
$files = scandir('uploads');
for($i=2; $i<count($files);$i++) {
    echo '<br>';
    print_r( $files[$i]);
}
?>

<script>
function func() {

    var id = prompt("<?php for($i=2; $i<count($files);$i++)echo $files[i];?>", "");

}
</script>

</body>
</html>

This loops through the array $files and prints it to the screen, I want to loop through the same array in a window.prompt object in javascript, and print the list to the prompt popup.

Before the end of the body tag:

<script>
function func() {
    var id = prompt("<?php for($i=2; $i<count($files);$i++)echo $files[i];?>", "");

}
</script>

But this seems to not print any of the array to the prompt object.

However if I do:

var list = prompt("<?php echo $files[2];?>", "");

It actually prints an element of the array, without the loop. But I want to print all at once, how can I accomplish this?

I tried using print_r() for the php code in javascript but that doesn't seem to make a difference.

printing the array at a exact position like $file[4] works, but using a for loop doesn't.

share|improve this question
    
you cant mix php and js like that. all the php is finished before any js starts. you could build a js array with the php, then loop that via js. – nogad Oct 30 '16 at 21:07
    
Why he couldn't, the php will do output to javascript on request, and the javascript will continue with static text – Ultrazz008 Oct 30 '16 at 21:08
    
prompt will contain every file, then run, it wont be a js loop – nogad Oct 30 '16 at 21:09
    
There's no js loop, he did loop through php and echoed to javascript, and it became a static text later. – Ultrazz008 Oct 30 '16 at 21:11
up vote 0 down vote accepted

Change i to $i, to be closer: $files[i] should be $files[$i]

var id = prompt("<?php for($i=2; $i<count($files);$i++)echo $files[i];?>", "");

use:

var id = prompt("<?php for($i=2; $i<count($files);$i++)echo $files[$i];?>", "");
share|improve this answer
    
Wow I feel like an idiot that I somehow missed that, thanks. – erere Oct 30 '16 at 21:10
    
You're welcome! – Ultrazz008 Oct 30 '16 at 21:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.