$.getJSON does not retrieve up-to-date information

Issue

I have a MySQL database set up. I have a PHP file that connects to the database and creates an array out of the database’s information. It then echoes that array encoded as JSON. I have an HTML file with JavaScript to retrieve this JSON and log it on the console.

The issue: When I run the HTML file after updating the table, it won’t show the new information. I have to manually run the PHP file that creates the JSON before running the HTML file for the console to show me the updated information. How do I get the HTML file to always retrieve the most up-to-date information from my database without running the PHP script manually?

Here is the PHP file (db.php):

<?php

include ("database_connect.php");

$sql = "SELECT * FROM markers";
$result = $conn->query($sql);

$array = array();
$i = 0;

while($row = $result->fetch_assoc()) {
    $array[$i] = $row;
    $i++;
}

echo json_encode($array);

$conn->close();

?>

Here is the HTML file (db.html):

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

</head>

<script>
$.getJSON('db.php', function(data) {
    console.log(data);
    }
);
</script>

</html>

Solution

You can’t put JQuery code in the script. You have to embed on onReady() call; otherwise, it will execute before HTML is loaded

$(document).ready(function(){
    $.getJSON('db.php', function(data) {
        console.log(data);
    });
});

Also, please remove the silly "disclaimer". Nothing wrong being new to development. As long as you read the tutorial you should be good. Such "disclaimers" are seen as an excuse to ask sloppy question; and you are actually less likely to get an answer!

Answered By – Felix

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published