0

I'm trying to figure out why the first code works whereas the second doesn't. I'm a tad green on jQuery and Javascript as a whole, but was under the impression that this "$('#location').html(...)" part populated the element with 'location' id. That way if I created a variable to which the results of the request are assigned, it'd do the same job if I had "$('#location').html(variable)". What gives?

Here are the two codes:

First Code(This works)

<!DOCTYPE html> 
<html> 
  <head> 
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Current Position</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  </head> 
  <body > 
    <div>Location: <span id="location"></span></div>
    <script>
      $.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?') 
         .done (function(location) {
            $('#location').html(location.city + ", " + location.state + " (" + location.country_name + ")");               
         });
    </script>
  </body> 
</html> 

Second Code(This one doesn't)

<!DOCTYPE html> 
<html> 
  <head> 
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Current Position</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  </head> 
  <body > 
    <div>Location: <span id="location"></span></div>
    <script>
      var currentLocation = $.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?') 
         .done (function(location) {
            location.city + ", " + location.state + " (" + location.country_name + ")";              
         });

      $('#location').html(currentLocation);   
    </script>
  </body> 
</html>
Collins Orlando
  • 1,521
  • 4
  • 18
  • 25

1 Answers1

2

$.getJson returns a kind of promise, not the value of the request itself. So assigning it's result to a variable won't give you the wanted results. This is the way most asynchronous stuff works. You won't ever be able to assign the result of an asynchronous call that way because the code hasn't successfully ran yet.

The first code it's the correct way to go. Think about it this way:

// Do some *asynchrounous* request
const promise = $.getJson(...arguments...)

// Create a handler funcion or "callback"
const handler = function(value) { console.log(value) }

// Tell the promise to call this function when it get's resolved
promise.done(handler);

Promises have some serious advantages like composability: multiple handlers can be attached.

$.getJson(...)
  .done(doStuffA)
  .done(doStuffB)
  .catch(handleError)
ichigolas
  • 7,595
  • 27
  • 50