Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Working with AJAX and JSON, but running into variable issues

I have been building a trivia game. I had a working version but want to keep iterating and making improvements.

One thing I was trying tonight was separating out a function I had written that pulled data out of my JSON file and build a series of arrays, and then used those arrays to display question on the web page. It worked before I split it, but now that I have split it into two functions (buildQuestionList and askQuestion) the questions are coming back as undefined.

I think this might be an issue of variable scope but I am not sure why it isn't working.

My workspace: https://w.trhou.se/7lckrw368p

I'd appreciate any help or advice!

I'am reading the code on mobile phone, so I might've missed it but do you ever fire your initialize function that should fetch the questions? I see it defined but I don't see where it's used :)

Can you give a link to the working version? I’d like to see

3 Answers

Well, I thought it was but apparently not! I was calling the initialize() function from the onclick behaviour in my HTML. I moved the code from the buildQuestionList into an $(document).ready function and it works now. Thanks for the tip! I am not totally sure why it wasn't firing properly the way I had it, but I am happy it works now.

Great! Cheers :)

Sure, @64yes, it is right here: http://davidjdrysdale.com/trivia/

It's working now but I am still looking to make improvements. The issue I want to resolve next is that the correct answers are accessible from the console if you access the correct variable. I have found a way to encrypt the answers but I've also been told it would be better to move checking to the server side. I don't know how to do that yet, so that's at the top of my list of things to learn.

Cool! Thanks for sharing. You can totally cheat with answers[questionNumber] :D

Yep... Apparently NodeJS can solve this, so that's what I'm trying to learn now!