I am using XMLHTTPRequest to get a JSON response. When I view the Response tab in Firebug, it shows me the JSON object, which I have validated on jsonlint. When I try to access the object's properties, I get
TypeError: obj is undefined
I have researched for several hours, but have not been able to find a working solution.
Code:
function getState(light) {
var txt = execute('GET', 'http://' + bridge + '/api/' + hash + '/lights/' + light);
var obj = eval('(' + txt + ')');
//var obj = JSON.parse(txt);
//this gives me "SyntaxError: JSON.parse: unexpected character"
console.log(obj.name);
}
function execute($method, $url, $message) { //used for both PUT and GET requests
var xmlhttp = new XMLHttpRequest();
xmlhttp.open($method, $url, true)
xmlhttp.send($message);
console.log(xmlhttp.response);
return xmlhttp.response;
}
In the Firebug Response tab, it indicates response of GET request: 200 OK -4ms
{
"state": {
"on": false,
"bri": 200,
"hue": 8664,
"sat": 140,
"xy": [0.4932, 0.3832],
"ct": 428,
"alert": "none",
"effect": "none",
"colormode": "hs",
"reachable": true
},
"type": "Extended color light",
"name": "Left rear living room 1",
"modelid": "LCT001",
"swversion": "65003148",
"pointsymbol": {
"1": "none",
"2": "none",
"3": "none",
"4": "none",
"5": "none",
"6": "none",
"7": "none",
"8": "none"
}
}
When I call my getState function (on pageload), the console.log claims that xmlhttp.response is an empty string. Doing typeof on 'txt' and 'obj' returns undefined. I'm trying to access the object elements, such as:
obj.name
and obj.state.on
I am new to using JSON and XMLHttpRequest - my code is based on a template someone else had initially created. I have no problem with PUT requests I used elsewhere in my program, using the above functions, but cannot seem to get GET requests working.
Please let me know if I left out any important info. Thanks for any help you can provide!
Your XML HTTP request is set to be asynchronous (i.e. the script doesn't wait until the response is received and continues while the HTTP request is happening in the background).
This means that there is not enough time for there to be an
xmlhttp.response
before you return it. As a consequence,txt
is undefined soobj
is undefined, just as the error message said.Change the
xmlhttp.open
call so that the call is synchronous (i.e. the script waits until the HTTP response is received before continuing):