KX Jaw
KX Jaw

Reputation: 141

Function not working if it have parameter

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?

Upvotes: 0

Views: 60

Answers (1)

vvartiainen
vvartiainen

Reputation: 11

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.

Upvotes: 1

Related Questions