0

I have the following function. When I click the first time, it returns a random number, but all subsequent clicks always return the same number. How come it doesn't refresh?

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {

        $('#btn-get-random-image').click(function () {

            $('#my-img').attr('src', '<?php echo $pics[array_rand($pics, 1)]; ?>');

        });
}); 
</script>

4 Answers 4

5

It's because you're using PHP to generate the random number, and it can't possibly be refreshed across calls to the JS function -- it's embedded in the HTML by that point.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, ok. So I need to be doing this with JS.
1

May be you can also use live like instead of click

  $(document).ready(function(){
    $('#btn-get-random-image').live("click", function () {
    // your works here
    }
 });

also check out jquery live

Comments

0

As others have said, you are using PHP, which is executed once on the server and sent as raw output, so the image will not change. Try this!

Edit: modified code to make it suck less.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var myPics = <?php echo json_encode($pics); ?>;
$(document).ready(function() {
    $('#btn-get-random-image').click(function () {
        var index;
        do {
            index = Math.floor(Math.random() * myPics.length);
        } while ( typeof myPics[index] == 'undefined' );
        $('#my-img')
            .attr('src', myPics[index]);
    });
}); 
</script>

This uses PHP's JSON encoder to dump your array to the javascript, then your function randomly selects an image from that array to display. The do/while loop might not be necessary, my testing shows a pretty good near-uniform distribution over thousands of iterations, but there it is nonetheless.

Comments

0

Your PHP is creating JS code, which gets sent to the browser once when the page is rendered. Each call to the JS function runs the function as it existed when the page was rendered.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.