0

I want to get city from the given api and display it. The output on console is undefined.This is what I have so far:

$.getJSON("http://ip-api.com/json", function(data1){

    city = data1.city;
     $("#city").html(city);

  });
    console.log(city);

How can I do this successfully?

Isaact
  • 75
  • 1
  • 10
  • 2
    In your case, you have an Asynchronous call, so when console.log is called city is undefined. you should move console.log within the success callback – Alcruz Sep 14 '17 at 01:03

1 Answers1

0

$.getJSON("http://ip-api.com/json", function(data1) {
  city = data1.city;
  $("#city").html(city);
  console.log(city);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="city"></div>
Will
  • 3,201
  • 1
  • 19
  • 17