I am trying to Pass an array from PHP to my Javascript using an HTTP request and JSON encode. However I keep getting this error message:
Uncaught TypeError: Cannot read property '132620' of undefined
(I tried calling number 132620 on the array.
This is my php code.
<?php
$myArray = array("num1","num2","num3",....);
$myJSON = json_encode($myArray);
echo $myJSON;
?>
And here is the beginning of my javascript code:
var getarray;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
getarray=JSON.parse(this.responseText);
console.log(typeof getarray); //for debugging
}
}
xmlhttp.open("GET","arrayhandling.php",true);
xmlhttp.send();
//and then later I call:
document.getElementById["h2"].innerHTML= getarray[1132620];
//and that's where I get the error.
I can't figure out what's wrong. Am I missing something? Here are some things I noticed while trying to figure out my mistake which might be helpful:
- typeof returns "object"
- I tried this just to see what would happen:
document.getElementById["h2"].innerHTML= getarray;
and it seems to be inputting the array into my HTML. In the HTML the header displayed the array. it displays num1,num2,num3,... without quotes or brackets before being cut off
I would appreciate help greatly as I've been stuck for a long time now. Thank you.
Btw I used this tutorial as a guide. https://www.w3schools.com/js/js_json_php.asp