I did the Random Quote machine project but I have a lot of duplicated code, badly written code.
I want to wrap the code up in functions, f.e:
function(get JSON data and parse)
function(set a quote and author)
function onclick(set a new quote and author)
I tried to re-do the project using Jquery and AJAX and am struggling with how the other functions can access the JSON data from the first function, as when I return the data, it is not accessible by the others… Very basic but I can’t figure it out…
I get you kinda want that order, but could you describe a bit more the reasoning for what you are trying to do? Your code looks fine at the minute btw, but would need to know what your aim is once you have a method you like for dealing with the data. Normal answer is write some functions to deal with the data in the way you want, and you call those inside the callback where you get the data.
Note, minor thing I noticed: success is in the range 200-299, so >= 200 and < 400 includes a whole range of failed request codes - the 300 range are redirects and stuff like “this page is no longer here, it’s moved to blah blah blah dot com”
EDIT: do you want to write is so it looks sequential (do this, then do this, then do this)? Because that’s what async/await is built for, so that your code becomes a lot easier to read. gimme a sec and I’ll do an example
Thank you for your reply!
Well I was aiming to lay-out the code in different functions so that it would be easier to read. Indeed sequential. Like in this example: https://codepen.io/freeCodeCamp/pen/qRZeGZ?editors=0010
Right now I have a lot of duplicated code such as
document.getElementById("text").innerHTML = "\"" + data.quotes[randomQuote].quote + "\""; to change the HTML to the data. I think it would be much easier if I put this in a function so it can be called.
Give me a while and I’ll try to make an example
Hmm, not quite sure. But I’ve done a very quick version of yours - I’ve tried to make the comments expain everything so see if it looks understandable:
Your code works just fine.
It is just that
gets executed before your JSON is parsed and loaded.
Make it use data after it is loaded and it will work just fine.