user5853060 user5853060 - 6 months ago 29
jQuery Question

Send PHP Array to Javascript and then select random images from array

Here's my PHP code:

$all_images = glob("Images/Classes/{*.png, *.PNG}", GLOB_BRACE);
echo json_encode($all_images);

And my Javascript code:

function Images(){
var i;
var z = Math.floor($('.Images').height() / 105); //Var z is the amount of images which fit in my div called .Images
var images = JSON.parse( '<?php echo json_encode($all_images); ?>' ); //Get Array from PHP which contains all images in the folder.
for (i = 0; i < z; i++) {
var a = document.createElement('a');
var noextension = images[i].substring(0, images[i].lastIndexOf("."));
var name = noextension.substring(noextension.lastIndexOf("/") + 1);
var final = "/Wiki/" + name + ".php";
a.setAttribute("href", final);
var x = document.createElement('img');
x.setAttribute("src", images[i]);
x.setAttribute("alt", name);
x.setAttribute("title", name);

I've finally made this program so it actually works, thanks to you guys, but I still have a problem. The problem is that the PHP Code pastes a line into the HTML code. But the PHP code shouldn't write anything. If as example I move the PHP code from the div Images to a different DIV, the array will pop up in that other div. So why is the PHP code writing something in the HTML code? And how can I prevent this? Error

EDIT: I fixed it by adding document.getElementsByClassName('Images')[0].innerHTML = ""; in javascript.


Try to include img inside anchor tag before. like this:


And then yours:


If I've understood you right, and error description too, it can't find the needed element with your desired structure