Reputation: 5
I'm new to JavaScript and I am stuck with this strange problem. When I try to parse JSON data into a variable, the variable becomes undefined.
My code:
document.getElementById('searchPlayerForm').onsubmit = searchPlayer;
function searchPlayer() {
var request = new XMLHttpRequest();
request.open(
"GET", '${url}' + '/' + document.getElementById('playerId').value, true
);
request.setRequestHeader('accept', 'application/json');
request.onload = responseAvailable;
request.send();
return false;
}
function responseAvailable() {
switch (this.status) {
case 200:
alert(this.responseText);
var playerResource = JSON.parse(this.responseText);
alert(playerResource.name);
...
The first alert returns:
{"playerID":49,"lastName":"XXX","firstName":"Walter","address":{"street":"XXX 2","city":"Eisden","postalCode":"3630"},"mobilePhone":"xxxx/xx.xx.87","phone":"xxx/xx.xx.39","email":"[email protected]","birthDate":"1948-10-11","rank":"D2","highestRank":"C6","memberSince":"1981","clubChampion":"1996","function":"Materiaalmeester","captain":"","linkVttl":"#http://competitie.vttl.be/index.php?menu=6&season=15&sel=14501&result=1&category=1#","currentMember":true,"currentIndex":10,"compNo":"507823"}
The second alert returns "Undefined".
Anyone who has a clue what might be the problem here?
Thanks in advance!
Diher
Upvotes: 0
Views: 229
Reputation: 1457
If you format the response, the answer becomes evident:
{
"playerID": 49,
"lastName": "XXX",
"firstName": "Walter",
"address": {
"street": "XXX 2",
"city": "Eisden",
"postalCode": "3630"
},
"mobilePhone": "xxxx/xx.xx.87",
"phone": "xxx/xx.xx.39",
"email": "[email protected]",
"birthDate": "1948-10-11",
"rank": "D2",
"highestRank": "C6",
"memberSince": "1981",
"clubChampion": "1996",
"function": "Materiaalmeester",
"captain": "",
"linkVttl": "#http://competitie.vttl.be/index.php?menu=6&season=15&sel=14501&result=1&category=1#",
"currentMember": true,
"currentIndex": 10,
"compNo": "507823"
}
As you see, there is no name
key, so accessing playerResource.name
will return undefined
.
Upvotes: 1
Reputation: 1720
There's no name
property in your json. There's lastName
and firstName
but no name
.
Upvotes: 1
Reputation: 19802
There is no name
key. Therefore, playerResource.name
is not defined. Try something like playerResource.firstName + playerResource.lastName
.
Upvotes: 0
Reputation: 24815
There is no property name
in the JSON
There is however a firstName, and lastName
To get full name, concat playerResource.firstName
and playerResource.lastName
var name = playerResource.firstName + ' ' + playerResource.lastName;
alert(name);
To prevent issues like this in the future, you can always do a console.log(playerResource)
to check what data you actually have. Or paste it to JSONLint
Upvotes: 3