I am trying to store a variable from an ajax get request calling a PHP script. I need the variable that the information is stored in to persist within an interval function. I see the data and the call is successful on the PHP script but the variable is undefined when I go back to the code that contains the ajax request. So my question is how do I go about storing this data into a variable and making sure the variable data is retained until I leave the webpage?
index.php
// ajax repeated call on home page
<script type="text/javascript">
var storedVariable0;
$(document).ready(function()
{
setInterval(function ()
{
// ensure data was retained will be undefined first time through
document.write(storedVariable0);
$.ajax({
url: '/fetchdatabase.php',
type: 'GET',
dataType: 'json',
})
.done(function(json){
storedVariable0 = JSON.stringify(json);
document.write(storedVariable0);
});
// ensure data is retained outside of the scope of the ajax call
document.write(storedVariable0);
}, 1000 ); //update every second
});
</script>
fetchdatabase.php
$sql = "SELECT content FROM messages ORDER BY id DESC LIMIT 1";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0)
{
// output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo json_encode($row);
}
}
thanks for any help