Reputation: 90
Hello there i wanted to request an api with ajax. The api has plain json (what i thought) now i set up an ajax request in javascript but i get an undefined error for the variables.I think i know the problem but I dont know an answer yet.
<script type="text/javascript">
document.getElementById("button").addEventListener('click', loadUsers);
// Load Github USers
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "dontKnowtheUrl", true);
xhr.onload = function()
{
if(this.status == 200){
var stats = JSON.parse(this.responseText)
var output = "";
for(var i in stats){
output +=
'<div class="user">' +
'<ul>' +
'<li>p_level: '+stats[i].p_level+'</li>'+
'<li>p_currentmmr: '+stats[i].p_currentmmr+'</li>' +
'</ul>' +
'</div>';
}
document.getElementById("users").innerHTML = output;
}
}
xhr.send();
}
This was the javascript part the json file from the api looks like this
{"results":
[{"p_id":"test",
"p_name":"test",
"p_level":"test",
"p_platform":"test",
"p_user":"test",
"p_currentmmr":"test",
"p_currentrank":"test",
"kd":"test"},
{"p_id":"test",
"p_name":"test",
"p_level":"test",
"p_platform":"test",
"p_user":"test",
"p_currentmmr":"test",
"p_currentrank":"test",
"kd":"test"}],
"totalresults":2}
My Guess is that the json file isnt a normal array because it contains the "results": and "totalresults" property. Does Anyone know how to fix it without getting into the json file?
Upvotes: 0
Views: 47
Reputation: 2589
You're going to want to loop through stats.results instead of just stats, see the following example:
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "dontKnowtheUrl", true);
xhr.onload = function()
{
if(this.status == 200){
var stats = JSON.parse(this.responseText)
var output = "";
for(var i in stats.results){
var row = stats.results[i];
output +=
'<div class="user">' +
'<ul>' +
'<li>p_level: '+row.p_level+'</li>'+
'<li>p_currentmmr: '+row.p_currentmmr+'</li>' +
'</ul>' +
'</div>';
}
document.getElementById("users").innerHTML = output;
}
}
xhr.send();
}
Upvotes: 1