Dynamically update HTML with getJSON

446 views Asked by At

I am rather new to both HTML and Javascript, but I've ran into a problem when I am trying to create a dynamical page. I am to update labels on a webpage by getting strings from a JSON-database every 5 seconds. My code looks something like this:

HTML:

<label id="tag1">0</label>

Javascript:

$(document).ready(function(){
  $.ajaxSetup({ cache: false });
  setInterval(function() {
    $.getJSON("js/database.json",function(data){
      if (data.tag1 == true) {
        $('#tag1').text(data.tag1);
      }
    });
  },5000);
});

This part I put after all blocks <body>

JSON:

{
    "database": [
        {
            "tag1": "<!-- AWP_In_Variable Name='\"database\".tag1' -->"
        },
        {
            "tag2": "<!-- AWP_In_Variable Name='\"database\".tag2' -->"
        },
        {
            "tag3": "<!-- AWP_In_Variable Name='\"database\".tag3' -->"
        },
        {
            "tag4": "<!-- AWP_In_Variable Name='\"database\".tag4' -->"
        },
        {
            "tag5": "<!-- AWP_In_Variable Name='\"database\".tag5' -->"
        },
        {
            "tag6": "<!-- AWP_In_Variable Name='\"database\".tag6' -->"
        }
    ]
}

Does anyone know what might be the problem? The webpage doesn't update the id tag1 at all.

Thank you in advance.

1

There are 1 answers

1
Praveen Kumar Purushothaman On

Small mistake in your accessing data. You need to check in the data['database']:

$(document).ready(function(){
  $.ajaxSetup({ cache: false });
  setInterval(function() {
    $.getJSON("js/database.json",function(data){
      data = data['database']; // You need to check in the first one!
      if (data.tag1 == true) {
        $('#tag1').text(data.tag1);
      }
    });
  }, 5000);
});