Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically call a php function in javascript

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!

like image 449
bryan Avatar asked Nov 30 '22 20:11

bryan


1 Answers

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.

like image 86
Paolo Bergantino Avatar answered Dec 06 '22 17:12

Paolo Bergantino