Outputing getJSON results once and they update every x seconds without the results repeating over and over
It's hard to decipher your question because there may be two different results of which one of them you're actually trying to achieve:
- have only the latest JSON result displayed (no change history)
- have only one JSON result per change displayed (history of changes)
The first one is simple and is as follows:
no history: Clear results before displaying them
Before you append your newly received results you have to clear previous ones.
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
setInterval(function(){
$.getJSON('names.json', function(data) {
$('#one').empty();
for(var i in data) {
$('#one').append(data[i]);
}
});
}, 5000);
</script>
change history: detect changes
Keeping change history has several different approaches:
First one has been somehow summarized by rogal111. Although his solution may not be best especially when the format of your resulting JSON changes, because his code only work when JSON results have at least those 4 fields defined. If any of them's missing an
undefined
will get displayed and if any additional one is added it will be omitted.A more dynamic solution is provided by Trinh Hoang Nhu that works with any JSON object's properties.
The third possible solution would be to call your Ajax URL by appending timestamp of the last change (
names.json/timestamp
) and if server sees that JSON has changed afterwards, it would send the object otherwise some default object would be sent over (i.e.false
ornull
) which would indicate that no change has been made...
load JSON data as per Key after certain time
Ok, I solved your problem.
Here is the code you sent me (Partly pasted):
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("demonew2.json",function(data){
$.each(data,function(key,value){
$("#topmost").append('<div>'+key+'</div>');
if(data.hasOwnProperty(key)){
//alert(key);
var total = new Array();
for(var i=0; i<4; i++){ // Here 4 should be something like counts of the keys, as in this json file it is 4
total[i] = key;
$("#topmost").append('<div>'+total+'</div>');
setInterval (function(){alert(key)},5000);
// I NEED THE DATA TO BE LOADED KEY BY KEY, SAY AFTER PAGE LOAD IT WILL DISPLAY THE VALUES OF key_1, THEN AFTER 5 SECONDS<br />
// IT SHOULD DISPLAY key_2 VALUES AND SO ON.
}
}
});
});
});
</script>
</head>
<body>
<div style="background:#ccc; border:2px solid #ccc; padding:10px;" id="topmost"></div>
</body>
There are 2 major problems laying in your code:
1) If you want a job to be done after a delay, you have to use "setTimeout" and not "setInterval" that repeats the job with the given interval.
2) using the same delay amount for all jobs will force them to be done almost the same moment so you have to increase the delay amount.
Additionally it would not be a good idea to pass the value directly to the setTimeout or setInterval methods as they start a new thread and there may be abnormal behaviors on cross-thread value injections, so I prefer using a proxy function to avoid ther direct injection and so here is the final working code:
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("demonew2.json", function (data) {
var delay = 0;
$.each(data, function (key, value) {
delay += 5000;
showData(key, value, delay);
});
});
});
function showData(key, value, delay) {
setTimeout(function () {
$("#topmost").append('<div>' + key + " = " + JSON.stringify(value) + '</div>');
}, delay);
}
</script>
</head>
<body>
<div style="background:#ccc; border:2px solid #ccc; padding:10px;" id="topmost"></div>
</body>
So let me know if this solved your problem or not.
Have fun. ;)
Update:
I added the full page code for you to use it easily, also changed the append part a little to have a fade effect and make it a little more fun:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("demonew2.json", function (data) {
var delay = 0;
$.each(data, function (key, value) {
delay += 5000;
showData(key, value, delay);
});
});
});
function showData(key, value, delay) {
setTimeout(function () {
$("#topmost").fadeOut(function() {
$("#topmost").append('<div>' + key + " = " + JSON.stringify(value) + '</div>').fadeIn();
});
}, delay);
}
</script>
</head>
<body>
<div style="background:#ccc; border:2px solid #ccc; padding:10px;" id="topmost"></div>
</body>
</html>
Is there anyway to update values in a JSON file after a certain interval of time?
With time.sleep()
you can do this. time.sleep()
delays your code for the amount of seconds that you specify, decimals are allowed. If you put it in a different thread, you can execute code whilst this is happening. This is some code for the threaded version, but you can remove threading by just calling updatedict()
import json
from time import sleep
import threading
values = {
"google":5,
"apple":4,
"msft":3,
"amazon":6
}
def updatedict():
while True:
global values
#incrementing values
for value in values:
values[value] += 1
#Writing file
with open("values.json","w+") as f:
f.write(json.dumps(values))
#Sleeping 1 minute
sleep(60)
#Starting new thread
threading.Thread(target=updatedict).start()
#Any code you wish to run at the same time as the above function
If you intend to run the script multiple times each incrementing onto what is already there, replace the existing values
variable assignment with
try:
with open("values.json") as f:
values = json.load(f)
#If the file is not found, regenerates values
except FileNotFoundError:
values = {
"google":5,
"apple":4,
"msft":3,
"amazon":6
}
Reading JSON each n second in Javascript
From the following code :
$.getJSON('static/mediciones2.json?'+ new Date().getTime(), function(data) {
setInterval(function() {
var lastKey = Object.keys(data).sort().reverse()[0];
console.log("ultimo" + lastKey);
$.each(data, function(key, value) {
//console.log(value[0]);
series.addPoint([value[0], value[1]], true, true);
});
}, 10000);
});
Clearly you are getting JSON file only once and onsuccess, you are parsing the same data after every 10 seconds.
You need to bring the setInterval out of getJSON.
setInterval(function() {
$.getJSON('static/mediciones2.json?'+ new Date().getTime(), function(data) {
var lastKey = Object.keys(data).sort().reverse()[0];
console.log("ultimo" + lastKey);
$.each(data, function(key, value) {
//console.log(value[0]);
series.addPoint([value[0], value[1]], true, true);
});
});
}, 10000);
I didn't test this.
May be the following URLs will give more help on fixing this :
- HighCharts Demo - Dynamically Update Data
- HighCharts Demo - Dynamically Update Data - JSFiddle
How to reload JSON with AJAX every 10 Seconds
You probably want the previous set of returned data replaced by the new set, instead of appending it. In that case, using jQuery you can do:
<div id='content'></div>
<script>
function loadChirp(){
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data) {
$('#content').html('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
});
setTimeout("loadChirp()",5000);
}
</script>
etc...
Update data from a new JSON after delay of 5 seconds and again from a new JSon after another 5 delays sec
Set it as a regular function and then call it from itself within the success handler so then you are never getting ahead of yourself. Then you can also just call it once from your $(document).ready.
var poll = function(){
$.ajax({
type:"GET",
url: "dummy.json",
success: function(data){
//HANDLE DATA
setTimeout(poll,5000);
}
});
}
Related Topics
Waiting Till the Async Task Finish Its Work
How to Completely Disable Selinux in Android L in the Init.Rc File
How to Delete Shared Preferences Data from App in Android
Recyclerview Cannot Be Scrolled
How to Resize the Avd Emulator Window in Android Studio
String Resource New Line /N Not Possible
Adb Is Not Detecting My Android Device on Ubuntu
Android: Open a Pdf from My App Using the Built in Pdf Viewer
Sending Files Using Post With Httpurlconnection
How to Set Button Click Effect in Android
How to Make My App Work in All Devices
Android Gradle Error When Sync Style Attribute Not Found
Android Volley Basicnetwork.Performrequest() Unexpected Response Code 404
Remove Apk from Library in Google Play Developer Console
Remove Green Border Around Android Application
How to Retrieve Current Fragment in Navhostfragment
How to Verify Purchase for Android App in Server Side (Google Play in App Billing V3)