I’m so stuck and confused with this. Googling doesn’t help me. After getting JSON data from openweathermap api:
temp.innerHTML=json.main.temp; works and it updates the respective span.
But temp = json.main.temp; and then temp.innerHTML =temp; doesn’t work.
Codepen Link: https://codepen.io/Smokahontas/full/OvorwK/
Note: Also, Chrome is giving me problem with reading json data. But in Firefox it works totally fine!
You change what temp is with the following line of code:
temp = json.main.temp - 273.15;
So after this line, temp is no longer the span element with id=“temperature”.
ahh… I’m so silly! Thanks Randell!
A common convention is to precede jQuery selectors (and some even do it with my vanilla JS selectors) is to precede them with a dollar sign. So:
var $temp = document.querySelector("#temperature");
That makes it really clear that you’re looking at a selector. It’s easy to remember becase $ is a synonym for jQuery.
Which raises the question - If you’re loading in JQ for the AJAX functions, why not use them for the DOM selectors?
So that line would be:
var $temp = $("#temperature")
That’s going to change how you access things with those selectors, but ya gotta learn sometime.
Thanks for this. Actually I’m trying to stay away from jQuery so as to do this only by pure JS or Vanilla JS as they say. But I had to use jQuery so as to do the $.ajax or $.getJSON method.
But yes, you’re right! I should be using full jQuery if I’m including it.
There is a debate about whether or not to use JQ. I think it’s good to learn both. But when you’re learning,mom think there’s nothing wrong with using JQ to start.
That being said, if you really don’t want to use JQ, there are alternatives to JQ AJAX functions. And now JS has the fetch function making it even easier to do with vanilla JS.
But going to the trouble of loading JQ just for the AJAX seems like buying a riding mower for the front yard but then using a non-powered push mower in the back. There are other libraries that deal just with AJAX that are not as heavy. Or you can just handle it with fetch.
Thanks a lot, Kevin for the explanation & also the links!
Whilst doing my quote app I discovered fetch and it works like a dream to obtain json data using vanilla js, so Kevin’s suggestion is spot on.