Reputation: 75
I'm trying to make a slideshow with jQuery, for this I try to get all of the images' urls stored in a folder without having to write them manualy It looks like I have to play around with Ajax, but I'm a bit confused I would basically like to get the var stored in an array in my PHP code
<?php
$dir = "img";
if (is_dir($dir)){
if ($dh = opendir($dir)){
$images = array();
while (($file = readdir($dh)) !== false){
if (!is_dir($dir.$file)) $images[] = $file;
}
closedir($dh);
}
}
$max = count($images);
So how could I quickly get the values of $images[]
in javascript? Anly help would be very appreciated! :)
Upvotes: 0
Views: 1330
Reputation: 4675
JS:
<script>
function loadPHP()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","somephp.php",true); //replace this with your file name
xmlhttp.send();
}
</script>
HTML:
<button onclick="loadPHP()">Click to load php</button>
<div id="myDiv"></div>
PHP:
<?php
$dir = "img";
if (is_dir($dir)){
if ($dh = opendir($dir)){
$images = array();
while (($file = readdir($dh)) !== false){
if (!is_dir($dir.$file)) $images[] = $file;
}
closedir($dh);
}
}
$max = count($images);
$toprint = "<ul>";
foreach($images as $x => $y){
$toprint .= ("<li>".$y."<br /></li>");
}
echo $toprint;
?>
Upvotes: 1
Reputation: 446
<?php
$dir = "img";
$images = array();
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if (!is_dir($dir.$file)) $images[] = $file;
}
closedir($dh);
}
}
header('Content-Type: application/json');
echo json_encode($images);
jQuery will automatically parse the JSON as long as the header content-type is set:
$.ajax({
'url' : 'imagelist.php',
'success': function(result) {
...
},
});
Upvotes: 2
Reputation: 27012
I'm not an expert at php, but I'm going to assume that $images
is an array of filenames. If not, change your code to also do that. Then at the end of your php file, add this:
echo json_encode($images);
Then in javascript, something like this:
$.get('imagelist.php').done(function(result) {
$.each(result, function(idx, image) {
console.log('found image: ' + image);
}
});
Upvotes: 1