How can I initialize the lastID
in jquery only first time with the value 0 because var lastID = 0;
does not work.
I have this ajax script in index.php
<script>
$(document).ready(function () {
var lastID = 0;
function getData() {
$.ajax({
type: 'GET',
url: 'data.php',
data: {lastID: lastID},
dataType: 'json',
success: function (data) {
lastID = data[0].id;
console.log(lastID);
$.each(data, function (i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.id),
$('<td>').text(item.name),
$('<td>').text(item.details)
).appendTo('#output');
});
}
});
}
getData();
setInterval(function () {
getData();
}, 10000); // it will refresh your data every 10 seconds
});
</script>
This is the url: 'data.php'
:
$sql = "select * from oders where id > ".$lastID." ORDER BY id DESC";
...
echo json_encode($dataArray);
With this query I get 0 results, and in console (console.log(lastID);
) I have no data.
If I change the query like this :
$sql = "select * from oders where id > 0 ORDER BY id DESC";
In console.log(lastID);
I get the correct last id. And in html I get the correct data and every 10 seconds it keeps adding same results over and over again.
I can't figure out how to initialize lastID first time as 0 (or the last ID in the database), and on every 10 seconds refresh, take the last ID from the ajax success data.