Reputation: 65
The code below generates json data dynamically from the database. When the data is generated it adds it to a specific div. How can i make the contents of JSONObject reload every 30 seconds. This will make it so that content shows changes in near real-time.
<script>
JSONObject = <?php echo include_once('../includes/dashboard-stats.php'); ?>;
document.getElementById("today_visits").innerHTML=JSONObject.todayVisits;
</script>
Below is the output of JSONObject = <?php echo include_once('../includes/dashboard-stats.php'); ?>;
JSONObject = {"todayEarnings":"2.60","todayVisits":"212","todayClicks":"36","todayLeads":"3","todayCalculateCR":"12%","todayEPC":"0.08","todayCTR":"17%","yesterdayEarnings":"0.40","yesterdayClicks":"35","yesterdayVisits":"148","yesterdayLeads":"1","yesterdayCalculateCR":"35%","yesterdayEPC":"0.03","yesterdayCTR":"24%","monthEarnings":"3.00","monthClicks":"75","monthVisits":"392","monthLeads":"4","monthCalculateCR":"19%","monthEPC":"0.05","monthCTR":"19%"}
1;
I tried using this to try and reload the json data.
<script>
function load(){
JSONObject = <?php echo include_once('../includes/dashboard-stats.php'); ?>
document.getElementById("today_visits").innerHTML=JSONObject.todayVisits;
setTimeout("load()",9000);
}
</script>
Upvotes: 1
Views: 375
Reputation: 378
Your PHP code Runs only One type Thats Why Result show Same. Use Ajax Call and Get New Data from DB through PHP FILE every 30 Second.
//Jquery Syntax
$.post("Your PHP SCRIPT FILE PATH HERE", { PARAMS you want to pass }, function( Get DATA FROM PHP FILE ) {
// HERE IS YOU Operation
},"DATA FORMAT");
==================================
//CODE Example
function loadStats(){
$.post( "../includes/dashboard-stats.php", { get:"stats" }, function(data) {
$("#today_visits").html(data.todayVisits);
}, "json");
}
$(function(){
loadStats();
setInterval(loadStats,9000);
}):
Upvotes: 2
Reputation: 3854
UPDATED THE ANSWER:
<script>
function load() {
var colors = ["#CCCCCC","#333333","#990099"];
var rand = Math.floor(Math.random()*colors.length);
$.getJSON("../includes/dashboard-stats.php", { get:"stats" },function(data) {
$("#today_visits").fadeOut().fadeIn().html(data.todayVisits).css("background-color", colors[rand]);
});
}
$(function() {
load();//on the page load.
setInterval(load,9000);
});
</script>
the url to ../includes/dashboard-stats.php is relative to the location of the page on which the script it present
Upvotes: 1
Reputation: 11375
With the jQuery library, we can do something like;
setInterval(load, 5000);
function load() {
$.get('../includes/dashboard-stats.php', function(ReturnData) {
JSONObject = ReturnData
});
}
setInterval
load
, create an ajax request to get the data.ReturnData
holds the output (HTML) of what is generated when ../includes/dashboard-stats.php
is triggered - try run it in your browser, and then find where the data is you're wanting to use.
"load()"
from line 1 after Moonwave commentUpvotes: 0