1

I have the following PHP code which selects 10 random people from the "network" table saying they have joined the chat:

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM network ORDER BY RAND() LIMIT 10";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo $row["name"]. " has joined the chat <br>";
}
} else {
echo "0 results";
}
$conn->close(); 

However, instead of just showing the full list of the 10 people, I want it to show each one individually for one second and fade between them. I have the following JQuery function to do this display, but I don't understand how to combine these. How do I put the 10 random records from the table into this function?

(function() {
var timesRun = 0;
var runLimit = 10;
var RandomPeople = [NEED THE 10 RECORDS FROM THE DATABASE ABOVE TO GO HERE],
i = 0;

setInterval(function() {
timesRun += 1;
if (timesRun < runLimit) {

$('#changing-word').fadeOut(function() {
$(this).html(RandomPeople[i = (i + 1) % RandomPeople.length]).fadeIn();
});
 }
}, 1000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="changing-word">Random Person's Name</span> has joined the chat.
drekbour
  • 2,895
  • 18
  • 28
  • 1
    Does this answer your question? [How do I pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-do-i-pass-variables-and-data-from-php-to-javascript#answer-23740549) Under the header `3. Echo the data directly to JavaScript` is what you're looking for. – WOUNDEDStevenJones Nov 06 '19 at 19:05

2 Answers2

1

Don't echo it, instead put in the variable and reuse in javascript part.

$rows = [];
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $rows[] = $row["name"]. " has joined the chat <br>";
    }
}

and in javascript part

var RandomPeople = <?php echo json_encode($rows); ?>
Vladan
  • 1,572
  • 10
  • 23
0

store the length of the array of random people and multiply it by 1000 that will be your seconds for setinterval var peoplearray = ['a','b','c']; var peopleJoined = peoplearray.length * 1000; // this will be your seconds now run it through setInterval and check condition (the way u r using timesRun) timesRun with length of the array if they are equal then use a function called clearInterval

that's all

  • Using `setInterval` is correct, but they're also asking how to populate the `RandomPeople` array, which your answer doesn't cover. Also, please utilize code formatting in your answer to make it easier to understand. – WOUNDEDStevenJones Nov 06 '19 at 19:04