简体   繁体   中英

Storing variable from ajax

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

Ajax by default is asynchronous. (synchronous is deprecating).

By asynchronous, it means that your third block of document.write(storedVariable0) will most likely be executed before the Ajax done block. So, you will get undefined before done has completed.

Doing asynchronous is recommended wau and you need change your way of coding and make sure all access to storedVatiable0 happened after done finishes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM