0

After requesting a json data i run it through function like this

request.onload = function() {
 var mainData = request.response;
 loadNavbar(mainData);
}
function loadNavbar(jsonObj) {
	length = jsonObj.catagories.length;
	for (var i = 0 ; i < length; i++) {
	list = document.createElement("li");
	span = document.createElement("span");
	itemName = mainData.catagories[i].catName;
	span.innerHTML = itemName;
	list.appendChild(span);
	nav.appendChild(list);
	console.log(i)
	}
}

the webpage return error like this:

main.js:21 Uncaught TypeError: Cannot read property 'length' of undefined
 at loadNavbar (main.js:21)
 at XMLHttpRequest.request.onload (main.js:12)

But after i change it to this :

request.onload = function() {
 var mainData = request.response;
 loadNavbar();
}
function loadNavbar() {
	length = mainData.catagories.length;
	for (var i = 0 ; i < length; i++) {
	list = document.createElement("li");
	span = document.createElement("span");
	itemName = mainData.catagories[i].catName;
	span.innerHTML = itemName;
	list.appendChild(span);
	nav.appendChild(list);
	console.log(i)
	}
}

It work accordingly. Can i know what i do wrong in the first snippet?

asked Apr 29, 2018 at 9:34
10
  • Could you share mainData as well ? Commented Apr 29, 2018 at 9:42
  • both code snippet is not working uncaught referenceError:request is not defined Commented Apr 29, 2018 at 9:49
  • may you log the mainDat in onload? in both codes. Commented Apr 29, 2018 at 9:52
  • 1
    There's no way your second piece of code could work that way. Do you have a gobal variable mainData? Commented Apr 29, 2018 at 10:00
  • i think you are wrong the first code may work but there is no way to second code to work. Commented Apr 29, 2018 at 10:03

1 Answer 1

1

I'm pretty sure the object you are passing to the function does not contain an array called catagories. I'm suggesting you have a typo there and it is supposed to be called categories instead.

However, more information could be useful. The contents of the mainData object, for example.

answered Apr 29, 2018 at 9:46
Sign up to request clarification or add additional context in comments.

2 Comments

this is the mainData
To me, it looks like you are passing in a JSON array instead of JSON object since the string starts with square bracket [ instead of curly bracket {. Try switching that?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.