Reputation: 23
I'm trying to set up a page that displays one row of information from a news DB at a time. It would display the first row for about 10 seconds, then swap to the next row of news for the same duration. I found an answer from five years ago that seemed as though it would work, but each time I try to run it one of my variables becomes unreadable due to it being undefined. Full code below:
<?php
include('include/sqlsettings.php');
$mysqli_conn = mysqli_connect($mysqli_host, $mysqli_user, $mysqli_pass, $mysqli_db);
$query = 'SELECT * FROM news';
$rs = mysqli_query($mysqli_conn, $query);
$info = array();
while($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)){
array_push($info, array('title' => $row['id'],
'news' => $row['news'],
'location' => $row['location']));
$infoData = json_encode(array('info' => $info));
file_put_contents('info.json', $infoData);
}
?>
<html>
<head>
</head>
<body>
<ul></ul>
</body>
<script src='/libs/js/jquery/jquery-3.2.1.min.js'></script>
<script>
var i = 0,
d = null,
x = null,
interval = 3000;
$(document).ready(function(){
fetch();
});
function fetch(){
// get the data *once* when the page loads
$.getJSON('info.json', function(data){
// store the data in a global variable 'd'
d = data.result;
// create a recurring call to update()
x = setInterval(function(){
update()
}, interval);
});
}
function update(){
// if there isn't an array element, reset to the first once
if (!d[i]){
clearInterval(x);
i = 0;
fetch();
return;
}
// remove the previous items from the page
$('ul').empty();
// add the next item to the page
$('ul').append(
'<li>' + d[i]['title']
+ '</li><li>' + d[i]['news']
+ '</li><li>' + d[i]['location']
+ '</li>'
);
// increment for the next iteration
i++;
}
</script>
</html>
The code errors out at if(!d[i])
kicking back with
Uncaught TypeError: Cannot read property '0' of undefined at update (<file>.php:33)
where d should be defined as the json data so I can loop through it. I'm not entirely sure what I'm doing wrong.
Upvotes: 2
Views: 311
Reputation: 539
You're assigning d
to to data.result
. If d
is undefined
, it is because data.result
is undefined. If it's possible for data.result
to be undefined
, consider doing the following check.
if(d && !d[i])
This will ensure d
is defined before checking the index.
Upvotes: 3