Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  155] [ 5]  / answers: 1 / hits: 31752  / 16 Years ago, tue, february 17, 2009, 12:00:00

I have an index.php with the following js function:



function returnImageString() {
return <?php include 'inc/image.functions.php'; echo getRandomImages(7); ?>; //This isn't dynamic; this will always return the same images. How do I fix this?
}


However, when the page loads, the php script is called and the result is added to the source code like this:



function returnImageString() {
return images/20.11.A1B9.jpg|images/8.14.47683.jpg|images/19.10.FBB9.jpg|images/21.12.9A.jpg|images/8.11.1474937909.jpg|images/8.15.99404.jpg|images/8.10.jpg|; //This isn't dynamic; this will always return the same images. How do I fix this?
}


What I want to happen is whenever I call the js function (returnImageString), I want it to call the php function each time (since the php function returns a string of random image locations) instead of having the string hardcoded in the js function.



Can someone point me in the right direction? Thanks!


More From » php

 Answers
2

This is not possible because you're mixing client-side behavior with server-side behavior. What you need to do is create an AJAX request to the server.



If you were using a library like jQuery (which you really want to, because it makes AJAX a breeze) you would do something like this:



PHP Code (maybe randomImages.php?)



// query for all images
// $_GET['limit'] will have the limit of images
// since we passed it from the Javascript
// put them all in an array like this:
$images = array('images/20.11.A1B9.jpg','images/20.11.A1B9.jpg',...);
print json_encode($images); // return them to the client in JSON format.
exit;


Client Side Javascript



function getRandomImages(limit) {
// make request to the server
$.getJSON('/path/to/randomImages.php', {limit: limit}, function(data) {
// data is now an array with all the images
$.each(data, function(i) {
// do something with each image
// data[i] will have the image path
});
});
}


Alternatively, if the amount of images is finite, you can skip all this crazyness and simply have an array with all the images and generate 8 random ones from the Javascript itself. This would probably be better for smaller data sets and even some bigger ones.


[#99963] Tuesday, February 10, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
teagan

Total Points: 98
Total Questions: 106
Total Answers: 101

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
teagan questions
Fri, Mar 5, 21, 00:00, 3 Years ago
Mon, Feb 15, 21, 00:00, 3 Years ago
;