Andreas Steiner
Andreas Steiner

Reputation: 66

Image wont change

I am trying to get the image links from 9gag (what also works) and when I click on a button the image changes to the next one. The basic problem is that it works only once. I can then switch between the 1st and the 2nd image, though. This should be pretty simple, but I ´ve got no clue where the error is, so thanks in advance to anyone bothering to look at this.

<?php 
    $index = 0
    $html = file_get_contents("http://www.9gag.com");
    preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
?>

<script>
    function nextImg(){
        <?php $index++;?>
        pic.src='<?php echo $gags[0][$index];?>'; 
    }
    function prevImg(){
        <?php $index--;?>
        pic.src='<?php echo $gags[0][$index];?>';
    }
</script>

Upvotes: 1

Views: 117

Answers (3)

Eric
Eric

Reputation: 907

You can't increment your PHP variables after the page has loaded. You are trying to increment them client-side with JavaScript. You are going to need to call that PHP using AJAX if you want to do this without refreshing the page, and even then you'll want to increment a javascript variable to keep track of where you are.

EDIT: I went a little nuts creating an ajax routine using PHP and JavaScript, specifically the jQuery library, which you will need to link to for this to work. You may also need to modify parts of the script to work with what you're trying to accomplish, but this certainly is a guide for running your ajax app as you're hoping to.

Start by making a PHP file with this script:

<?php
    // Set content header to json
    header('Content-Type: application/json');

    // Get the index from the AJAX
    $index = $_GET['index'];

    // Grab file contents & parse
    $html = file_get_contents("http://www.9gag.com");
    preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);

    // Send filename back to AJAX script as JSON
    echo json_encode(array($gags[0][$index]));
?>

Then, in your HTML, include this jQuery to complete AJAX calls to your PHP script, and update the DOM with the data from the PHP script.

<script>
            $(function() {
                'use strict';

                // Initiate index variable
                var index = 0;

                // Load initial image
                loadImage(index);

                // Add click event to a button with class of next-btn
                $('.next-btn').click(function(e) {
                    e.preventDefault();

                    // Increment index to get next image
                    index++;

                    // Run AJAX function to retrieve image
                    loadImage(index);
                });

                // Add click event to a button with class prev-btn
                $('.prev-btn').click(function(e) {
                    e.preventDefault();

                    // Decrement the index if it isn't 0
                    if (index > 0) {
                        index--;
                    }

                    // Run AJAX function to retrieve image
                    loadImage(index);
                });
            });

            function loadImage(index) {
                'use strict';
                $.ajax({
                    type: 'GET',
                    url: 'your-php-script.php', // Filepath to your PHP script
                    data: 'index='+index, // Index is passed through GET request
                    dataType: 'json', // Return JSON
                    success: function (data) { // If the php script succeeds
                        // Change img with class of pic's src 
                        // to the filename retrieved from php
                        $('.pic').attr('src', data[0]);
                    }
                });
            }
        </script>

Configuring this for your needs will require some serious PHP and jQuery/JavaScript knowledge, as some debugging will likely be needed. Good luck!

EDIT 2: I uploaded the working (tested, it works) source files to my website if you want to download. Please accept answer and let me know you grabbed the files...

http://www.wedgewebdesign.com/files/ajax-image-loader.zip

Upvotes: 3

Grambot
Grambot

Reputation: 4514

@Eric basically has it right but didn't really go into detail if you aren't familiar with the model...

PHP is a server side language in that it does all its processing on the web host server and once it is complete sends a static result back to the user. This means, whatever you see after the page is loaded within PHP is there to stay, unless you do one of two things:

1) Send a new request -- You provide different parameters, the page re-executes its logic and returns a new result to the user

2) Execute some form of clientside Javascript. Javascript is different from PHP in that it executes on the client (not the server) so you don't necessarily have to send responses back to the server unless you need more information. Javascript and PHP can be combined to create AJAX calls which allow the client to make asynchronous calls to the webserver for more data without reloading the entire page. The Javascript handles re-drawing the new information or updating the page which can appear seamless to the user.

What you therefore need is one of those two options. Either you provide 'next'/'previous' links to the user and the page is loaded differently each time or you create an AJAX call that fetches the url of the next image and then loads it.

Upvotes: 2

Charles
Charles

Reputation: 4528

Try assigning a variable to $gags[0][$index]. Something like

$imgsrc = $gags[0][$index];

and then

pic.src='<?php echo $imgsrc; ?>';

Upvotes: -1

Related Questions