Some information – I’m creating an autocomplete which gets the data from a json feed. The JSON part works fine and the result is valid.
When I’m obtaining it, I’m using json2.js and running JSON.parse. When I try and output it tells me that it (the object containing the parsed JSON text) is actually undefined.
If I run an alert on the object and then output it works. It’s probably something quite simple. But this is the bit that is confusing as it works fine if I alert the object
I know that it won’t work on everything, I’m just trying to get it working for now and I’ll improve it.
Thank you and if there is any more information I can provide I will.
The code
//sURL takes a search term that's passed into the function
var JSON_object = {};
var oRequest = new XMLHttpRequest();
var sURL = "datalinkhere"+input.value;
oRequest.open("GET",sURL,true);
oRequest.setRequestHeader("User-Agent",navigator.userAgent);
oRequest.onreadystatechange = function () {
if (oRequest.readyState == 4 && oRequest.status == 200)
{
JSON_object = JSON.parse( oRequest.responseText );
}
};
oRequest.send(null);
suggestion(JSON_object,input);
function suggestion(inp,targetid)
{
document.getElementById('autosuggest').style.display='block';
document.getElementById('autosuggest').innerHTML=inp[1].namefield;
}
The problem ist not alerting the json or not it’s the concept of your code. Ajax requests work asynchronously, thus your oRequest.send call will not block until the data has been loaded, the data is loaded in the background.
So you can have luck and the data is available when the next line (suggestion-call) and your code works or you will get an undefined var.
You’ll have to write your code asynchronously: Put the suggestion-call direcly after the JSON.parse-call and all will work like a charm.