Reputation: 11
Currently working on a website project for my portfolio and I've recently gotten a javascript and jquery book to help me learn this new language since I'm already familiar with HTML and CSS+Sass.
The project I'm working on involves accessing an in-domain JSON file that holds some simple data that I want to display in HTML format using ajax, but the only problem is that I'm getting this error 'Uncaught TypeError: Cannot read property 'length' of undefined'.
Any help would be appreciated!
javascript / ajax
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
responseObject = JSON.parse(xhr.responseText);
var project;
for (var i = 0; i < responseObject.events.length; i++) {
//for loop
project = '<div class="display-item>';
project += '<div class="title">' + responseObject.events[i].name + '</div>';
project += '<div class="sourcelink">' + responseObject.events[i].source-code-link + '</div>';
project += '<div class="livelink">' + responseObject.evetns[i].live-link + '</div>';
project += '<div class="isPrivate>' + responseObject.events[i].isPrivate + '</div>';
project += '<div class="isLive">' + responseObject.events[i].isLive + '</div>';
project += '</div>';
}
//Update page with new content
document.getElementById('openSourceContent').innerHTML = project;
}
};
xhr.open('GET', '../js/data/htmlProjects.json', true); //Prepare request
xhr.send(null); //Send request
json being processed
{
"projects" : [
{
"name" : "Minimalist Template 1",
"source-code-link" : "https://github.com/CandyPheonix/html5-minimalist-template",
"live-link" : "https://candypheonix.github.io/html5-minimalist-template/",
"isPrivate" : "false",
"isLive" : "true"
},
{
"name" : "Minimalist Template 2",
"source-code-link" : "https://github.com/CandyPheonix/html5-minimalist-template-2",
"live-link" : "https://candypheonix.github.io/html5-minimalist-template-2/",
"isPrivate" : "false",
"isLive" : "true"
}
]
}
My expected result is to have ajax read the JSON file data and parse it into HTML ready code so it can be displayed on the browser, but it gives me that 'length' of undefined error.
error that occurs in the console: **Uncaught TypeError: Cannot read property 'length' of undefined at MLHttpRequest.xhr.onload (jsonDecompileToHTML.js:8)
xhr.onload @ jsonDecompileToHTML.js:8
load (async)
(anonymous) @ jsonDecompileToHTML.js:2**
ps. sorry for not using jQuery, I'm still learning!
Upvotes: 0
Views: 2269
Reputation: 11
First off, I want to point out how much of a rookie mistake this was by saying that just one random comment telling me that responseObject doesn't use a property called "events", I realized that, that is were the name of the JSON array is supposed to go.
ps. another thing I found out the hard way is that you can't use a key with "-" in the separating words, it's just better to just use "exampleExample".
This just shows that not even a direct answer can help you solve a problem, lol.
Upvotes: 0