Christopher Sheffield Christopher Sheffield - 4 months ago 31
Javascript Question

Undefined array error (javascript) using php/ajax/json etc

I have a simple website here. It contains a div item with a css object inside. Im trying to use ajax and json to run a php script that will grab a value out of a text file and update the div item with said value. Problem is passing dataList[0] to a the function "replaceContentInContainer()" comes up as an undefined error in console.

Here is the script that is throwing the error. It throws it as soon as dataList[0] is referenced.

<script>
setInterval(function()
{
$.getJSON('loadData.php', function(data){
var dataList = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
dataList = data.value;
var tempID = "tempDIV";
console.log('Good to go, data was loaded');
console.log(data);
ReplaceContentInContainer(tempID,dataList[0]);
}
}, 2000);
</script>

<script type="text/javascript"><!--
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
//--></script>


the PHP file

<?php
$lines = file("data.txt");
echo json_encode($lines);
?>


Data File format 'data.txt'

78\n
82\n
33\n
etc...


Console output as follows

Good to go, data was loaded indexUpdate.php:30:5
Array [ "75 ", "34 ", "0 ", "0 ", "80 ", "31 ", "60 ", "72 ", "60 ", "70 ", 8 more… ] indexUpdate.php:31:5
TypeError: dataList is undefined
indexUpdate.php:32:5
Good to go, data was loaded indexUpdate.php:30:5
Array [ "75 ", "34 ", "0 ", "0 ", "80 ", "31 ", "60 ", "72 ", "60 ", "70 ", 8 more… ] indexUpdate.php:31:5
TypeError: dataList is undefined


It doesnt make sense why it thinks my array is undefined or at least why I am not allowed to define the element by a index.

Answer

dataList = data.value; should be dataList = data; as you're not returning an object, so there is no value property.

Comments