0

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:

  1. typeof returns "object"
  2. 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

cactus
  • 69
  • 1
  • 1
  • 8
  • 1
    on a 2021 note: use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) rather than XMLHttpRequest. It's infinitely better at getting various types of data, and "just works" without any of the ridiculous code we needed for XHR in the past. `fetch("your url").then(response => response.json()).then(result => doThingsWithYourData(result)).catch(e => console.error(e))`. Also, don't use `innerHTML`, use `.textContent` if you want text, and use DOM functions (createElement, append, etc) if you need DOM nodes. – Mike 'Pomax' Kamermans Feb 10 '21 at 21:15

1 Answers1

1

the Problem is your using an not synchron request.

The document.getelement..... part does not wait for the answer of the request. So you have to put it in the callback function of the request

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
Haennie
  • 40
  • 4
  • Thank you that makes sense. I think I can put all my array handling functions into the php and then only give the elements i need to js, that might make things easier. Thank you – cactus Feb 10 '21 at 21:36