1

Cannot declare global variable inside this jquery method. What I am missing and how to do it?

var info = "empty";
 
$.get("http://ip-api.com/json", function(response) {
  info = response.city;
 }, "jsonp");
 
 console.log(info);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rasul
  • 121
  • 2
  • 3
  • 7
  • `$.get` is async method so your `console.log` will show initial value.Put `console.log` inside `$.get` and you will see updated value, – Mairaj Ahmad Dec 29 '16 at 05:40

1 Answers1

2

You can set the variable like

var info = "";

$(document).ready(function(){
    $.get("http://ip-api.com/json", function(response) {
        info = response.city;
        console.log(info);
    }, "jsonp");
}); 
Kirankumar Dafda
  • 2,354
  • 5
  • 29
  • 56