0

Here is my function:

var myVar = setInterval(myTimer, 500);
function myTimer() 
{
    xhttp=new XMLHttpRequest();
    xhttp.onreadystatechange = function() 
    {
        if (this.readyState == 4 && this.status == 200) 
        {
            x=this.responseText;
            window.alert("x,jsondata="+x);
            var jsondata = JSON.parse(x);
            document.getElementById("1").innerHTML = jsondata[0].1;
            document.getElementById("2").innerHTML = jsondata[0].2;
            document.getElementById("3").innerHTML = jsondata[0].3;
            document.getElementById("4").innerHTML = jsondata[0].4;
            document.getElementById("5").innerHTML = jsondata[0].5;
            document.getElementById("6").innerHTML = jsondata[0].6;
            document.getElementById("7").innerHTML = jsondata[0].7;
            document.getElementById("8").innerHTML = jsondata[0].8;
            document.getElementById("9").innerHTML = jsondata[0].9;
        }
    }
    xhttp.open("GET", "getData.php?q="+<?php echo $fileToAccess;?>, true);
    xhttp.send();
}

This is getData.php:

<?php
    $file=$_REQUEST['q'];
    $myfile=file_get_contents($file);
    $json=json_decode($myfile);
    echo $json[1];
?>

and this is how my json file looks like:

[{"str": "user2"},{"1": "","2": "","3": "","4": "","5": "","6": "","7": "","8": "","9": ""}]

I added a timer to constantly update the values of my buttons with the help of the json file. But I am getting the error at line

document.getElementById("1").innerHTML = jsondata[0].1;

artgb
  • 3,177
  • 6
  • 19
  • 36
  • You can only use **dot notation** for accessing a property, if the property name was a valid *variable name*. You cannot use *numbers* as variable names (i.e. `var 1 = 'foo';` is not valid). Hence you have to use **bracket notation**. – Felix Kling Oct 26 '17 at 01:09

1 Answers1

1

You're pretty right in what you're doing. But since the key is numeric, you have to fetch it with ['1'] instead. Like this:

document.getElementById("1").innerHTML = jsondata[0]['1'];

In Javascript there's mainly two ways to get a property from an object

obj.prop

and

obj['prop']

Generally you can say that obj.prop will only work if the property is valid variable name (doesn't contain special characters, numeric, etc).

kontrollanten
  • 2,649
  • 19
  • 32
  • *"But since the key is a number (of type string)"* That's a bit confusing. Lets just say the key is *numeric*. – Felix Kling Oct 26 '17 at 01:08
  • 1
    *"`obj.prop` will only work if the key is not numeric"* That's not quite right. There are many other cases where you cannot use dot notation, e.g. if the property name contains a space. You can only use dot notation if the property name is a valid variable name (or a keyword). – Felix Kling Oct 26 '17 at 01:10
  • 1
    "*obj.prop will only work if the key is not numeric, since JS can't recognize it.*" - Technically it's because the formal syntax does not allow it. – Derek 朕會功夫 Oct 26 '17 at 01:10