1

I have 12 users in a MySQL table. Their IDs could be anything as their IDs are randomly generated (but that's another story).

For convenience's sake, let's pretend the IDs are 1-12.

I also have user profile photos stored in a directory:

Directory = data/profiles/users/profile_img/{USER_ID}/main.jpg

I am running a MySQL query (works fine) to fetch all 12 users user_ids. I am then passing these IDs into a jquery array and putting them through a function that randomises the order these are shown on the page as images by changing the image class src attribute - this bit's done using jQuery.

Note I am using random function because I only want 6 out of the 12 results to be shown at any given time and in random order.

This works and the images are shown, in random order, and rotate/change every 5 seconds.

However, surrounding my image is a href class 'premium_component_link'. And I want to link each profile image to its corresponding user profile page.

I have tried to do this by using this parent like so:

$(this).parent(".premium_component_link").attr('href','profile.php?p_id=' + displayImage()) 

The problem I have is that displayImage() is re-generating a separate random user_id and so the image being displayed does not correlate with the profile link when the user clicks it.

Slightly off topic but eventually I'm also going to want to get the users name and location from my table where the user_id matches and place these in between my classes "h3 class="mt-4" - but I have no idea how i'm going to do this yet and do not think i should run before I walk.

Is there anyway I can pass one instance of displayImage() into these two attributes href and src together during each occurrence of the function?

Code:

<?php $result = $conn->query("SELECT  * FROM user_data WHERE advert_type = 'Deluxe'");
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) { 
$p_id = $row['user_id'];

$new_array[$p_id] = $row['user_id'];


echo '<script>';
echo 'var imagesArray = ' . json_encode($new_array) . ';';
echo '</script>';            
?>    


<script>

var usedImages = {};
var usedImagesCount = 0;

var imageIndexes = [0,1,2,3,4,5,6,7,8,9,10,11]

function displayImage() {
    var index = Math.floor(Math.random() * (imageIndexes.length));
    var num = imageIndexes[index]

    var result = imagesArray[num];
    imageIndexes.splice(index, 1)

    if (imageIndexes.length === 0) {
        imageIndexes = [0,1,2,3,4,5,6,7,8,9,10,11]
    }
    return result
}


function changeImagesSrc() {

    $(".premium_ad_img").each(function () {
        $(this).attr('src','data/profiles/users/profile_img/' + displayImage()) + '/main.jpg')       
        $(this).parent(".premium_component_link").attr('href','profile.php?p_id=' + displayImage())
    }) //End Change IMage


} //End Function Change

$(document).ready(function () {

    changeImagesSrc()
    setInterval(function() {
        changeImagesSrc()
    }, 5000);
})

</script>

<? } } ?>



<?php 
//Echo out results
echo '<div class="premium_component"><a href="" class="premium_component_link">';
echo '<img class="premium_ad_img" src="" height="auto" width="auto" />';
echo '<div class=" choose-grid"><h3 class="mt-4">Mark London</h3><p class="">25, London UK</p></div></a></div>';

echo '<div class="premium_component"><a href="" class="premium_component_link">';
echo '<img class="premium_ad_img" src="" height="auto" width="auto" />';
echo '<div class=" choose-grid"><h3 class="mt-4">Mark London</h3><p class="">25, London UK</p></div></a></div>';

echo '<div class="premium_component"><a href="" class="premium_component_link">';
echo '<img class="premium_ad_img" src="" height="auto" width="auto" />';
echo '<div class=" choose-grid"><h3 class="mt-4">Mark London</h3><p class="">25, London UK</p></div></a></div>';

echo '<div class="premium_component"><a href="" class="premium_component_link">';
echo '<img class="premium_ad_img" src="" height="auto" width="auto" />';
echo '<div class=" choose-grid"><h3 class="mt-4">Mark London</h3><p class="">25, London UK</p></div></a></div>';

echo '<div class="premium_component"><a href="" class="premium_component_link">';
echo '<img class="premium_ad_img" src="" height="auto" width="auto" />';
echo '<div class=" choose-grid"><h3 class="mt-4">Mark London</h3><p class="">25, London UK</p></div></a></div>';

echo '<div class="premium_component"><a href="" class="premium_component_link">';
echo '<img class="premium_ad_img" src="" height="auto" width="auto" />';
echo '<div class=" choose-grid"><h3 class="mt-4">Mark London</h3><p class="">25, London UK</p></div></a></div>';



?>
halfer
  • 19,824
  • 17
  • 99
  • 186
M. Obren
  • 31
  • 1
  • 7

2 Answers2

1

For your javascript tag, you really just need a shuffle function and an all-inclusive changeComponent function that does all the work each interval heartbeat. Also, you'll notice that jQuery has a more useful version of the each() function that provides the index of the current element:

<?php $result = $conn->query("SELECT  * FROM user_data WHERE advert_type = 'Deluxe'");
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) { 
        $p_id = $row['user_id'];
        $new_array[] = $p_id;
    }
}

echo '<script>';
echo 'var imagesArray = ' . json_encode($new_array) . ';';
echo '</script>';            
?> 

<script>
//Good shuffle algorithm: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
    function shuffle(array) {
        var currentIndex = array.length, temporaryValue, randomIndex;

        // While there remain elements to shuffle...
        while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }

        return array;
    }

    function changeComponent() {
        // store image query in a variable
        var $allImages = $(".premium_ad_img");
        // take X random IDs by shuffling the list and taking the first X
        // (slice total dynamically, in case you ever need more or less than exactly 6)
        var randomIDs = shuffle(imagesArray).slice(0, $allImages.length);

        // iterate over each image, using the index of the iteration.
        $allImages.each(function (idx) {
            $(this).attr('src', 'data/profiles/users/profile_img/' + randomIDs[idx] + '/main.jpg');
            $(this).parent(".premium_component_link").attr('href', 'profile.php?p_id=' + randomIDs[idx]);
        });
    }
    $(document).ready(function () {

        changeComponent();
        setInterval(function() {
            changeComponent();
        }, 5000);
    })
</script>
somosomo
  • 76
  • 4
  • thanks this seems to be working a lot smoother now. However same issue i pointed out to our friend @Nawed Khan. Not all the user_ids in my mysql tables are 1-12. This was just an example given. My user_ids are 8 digit integers like 12345678 or 0134546. They're not going to be 1-12. And at the moment when i test the code, it works on user_ids 1-12 but not on user_id 44456784 for example. I think this has something to do with the imageIndexes. Is there a way to change this to accommodate this requirement? thanks – M. Obren Mar 19 '19 at 23:08
  • @M.Obren I see; I've corrected my answer to shuffle your actual imageArray. However, for this to work with your PHP, you have to change this: `$new_array[$p_id] = $row['user_id'];` to this: `$new_array[] = $p_id;` which will continually append your $p_id elements to the end of the array. – somosomo Mar 20 '19 at 05:03
0

You can store the result of displayImage() to a variable and use it as many times as you wish without having to call the function again. That is the most basic programing concept... like crawling (in your terms).

   function changeImagesSrc() {

            $(".premium_ad_img").each(function () {
               var display = displayImage();
               $(this).attr('src','data/profiles/users/profile_img/' + display + '/main.jpg');       
               $(this).parent(".premium_component_link").attr('href','profile.php?p_id=' + display);
            }); 
    }

Your array index are same as the user id but in your javascript you are looping from 1 thru number_of_images. You need to index your array as 0 thru number_of_records... do the following:

replace this:

while($row = $result->fetch_assoc()) { 
$p_id = $row['user_id'];

$new_array[$p_id] = $row['user_id'];

with this:

$i = 0;
while($row = $result->fetch_assoc()) {    
   $new_array[$i] = $row['user_id'];
   $i++;
}
Nawed Khan
  • 4,393
  • 1
  • 10
  • 22
  • thank you for this. However, I did initially try storing it as a variable... but for some reason the jquery stops running entirely. Same issue when i try with your code unfortunately – M. Obren Mar 19 '19 at 22:31
  • that seems to be working now. Although say i have a user with the user_id 100, this will not show. Is that because of the ImageIndexes set 0 - 11 in the variable? If so, is there a way i can improve this to accomodate any integer value 0-1000 or higher? The fact is there are only 12 users in total in the table, however their user_ids are not always 1-12. Any way you could offer additional support on this? – M. Obren Mar 19 '19 at 22:47
  • That is because your array index are same as the user id but in your javascript you are looping from 1 thru number_of_images. You need to index your array as 0 thru number_of_records. I have updated the code to include that. – Nawed Khan Mar 19 '19 at 23:15
  • I'm confused. How do i implement this code? Am i removing Var usedImages Count ? if i do that then where are the mysql results being passed into the javascript? – M. Obren Mar 19 '19 at 23:49
  • @Newad Khan please look at my code edit attached in your answer. Please check that I am implementing correct? – M. Obren Mar 19 '19 at 23:53
  • The second part (code) of my answer is the replacement for your php code. It replaces the while loop right before the echo ' – Nawed Khan Mar 20 '19 at 00:03
  • please forgive my ignorance as i'm brand new to javascript. But how am i assigning this? – M. Obren Mar 20 '19 at 00:07
  • I've updated the answer. Just replace the 3 lines of php with 5 lines of php code. – Nawed Khan Mar 20 '19 at 00:12
  • UPDATE: ok so here's what's happening now. All user_ids are pulling through. However, i am sometimes getting an undefined user_id. What could be causing this? – M. Obren Mar 20 '19 at 00:26