Reputation: 1285
I have a <body style="<?php include("gallery.php"); ?>"
where gallery.php holds a random array of images, echoing the URL upon each reload.
I would like to have a button to refresh the background image of the body.
I currently am able to do one reload of the image, since the new URL is echoed.
EG:
$(".refresh").click(function() {
$("body").css("background-image", "url(<?php include("gallery.php"); ?>)");
});
But after the inclusion of the gallery file in the script, it is always the same url.
EDIT My PHP is as follows:
$bg = array(
array( "url" => "url_1" ),
array( "url" => "url_2" ),
...
);
for ($i=0;$i<1;$i++) {
$id = array_rand($bg);
echo "{$bg[$id]['url']}";
unset($ad[$id]);
};
Upvotes: 0
Views: 859
Reputation: 4705
It would be in an another way and gallery.php
could outputs an image (not just a url), So you can access gallery.php
like this :
$(".refresh").click(function() {
$("body").css("background-image", 'url("http://www.mysite.com/gallery.php?'+Math.random()+'")');
});
Using Math.random()
will passes a random number to avoid caching.
So in gallery.php
you have something like :
$bg = array(
array( "url" => "url_1" ),
array( "url" => "url_2" ),
...
);
shuffle($bg); // Random order
echo file_get_contents($bg[0]['url']);
//instead of echo $url;
Upvotes: 2
Reputation: 17797
IMO Ajax is overkill and piping all images through a php script creates unnecessary memory overhead. For very large images it could even create memory problems on your webserver. The best method would be to put all images in a javascript array, as already suggested. You can have gallery.php
output an array of URLs to the images.
[ 'http://url1/', 'http://url2', ... ] // etc
Then you can call it in your file like this:
<script type="javascript">
var backgroundImages = <?php include("gallery.php"); ?>;
function refresh() {
$("body").css("background-image", "url(" + backgroundImages[Math.round(Math.random() * backgroundImages.length)] + ")");
}
$(function() { refresh(); });
$(".refresh").click(refresh);
</script>
Upvotes: 0
Reputation: 10030
$(".refresh").click(function() {
$.get('gallery.php', function(data) {
$("body").css("background-image", "url('"+data+"')");
}
});
PHP is server side scripting language and Javascript is client side scripting language. We can't use them like you were using. But you can send request from client to server to faciliate body with URL.
Upvotes: 1