I had a previous problem solved on stackoverflow but the requirments of my project have changed so I need a new solution. To summerise I have a getJSON function that executes every 5 seconds to read for change in a JSON file. The problem I am having is outputting the data correctly. I want the data to output once but update every 5 seconds in case the user makes changes to the JSON file
Here is my code
<script type="text/javascript">
$.ajaxSetup({
cache: false
});
setInterval(function() {
$.getJSON('names.json', function(data) {
for (var i in data) {
$('#one').append(data[i]);
}
});
}, 5000);
</script>
This getJSON function allows me to grab JSON data and append it to the start of a div. Then I refreash the function so that if the JSON data changes then the data changes in the div. The problem is that the data repeats itself every 5 seconds.
The unexpected result after 15 seconds
453545Beady little eyesLittle birds pitch by my doorstep
453545Beady little eyesLittle birds pitch by my doorstep
453545Beady little eyesLittle birds pitch by my doorstep
The result I want after 15 seconds
453545Beady little eyesLittle birds pitch by my doorstep
If I change the JSON 11 seconds when the script is running
"two": "Eyes"
The result I want to get after 15 seconds
453545 Eyes Little birds pitch by my doorstep
Rather than the actual result I get after after 15 seconds
453545Beady little eyesLittle birds pitch by my doorstep
453545Beady little eyesLittle birds pitch by my doorstep
453545 Eyes Little birds pitch by my doorstep
Here is the JSON file I am using
{
"one": "453545",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Hopefully I have made this as clear as possible
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:
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.
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
undefinedwill 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.falseornull) which would indicate that no change has been made…