0

I have created a global variable in jquery. then i created a function in which i making jquery get call and setting the response var to global variable. when i am doing console.log to that global var, it is showing blank always. the code i did is

var currentname = "";
function getcurrentname() {
    $.get(
        url
    ).success(function(response) {
        response = JSON.parse(response);
        currentname = response.name;
    });
}
getcurrentname();
console.log(currentname);

so what should i do use that variable globally.

  • `.get()` is asynchronous so your `console.log` is executed before the .`get()` finishes. Move the `console.log` into the success function. – j08691 Jul 25 '17 at 16:05
  • then how will i be able to use that global variable. – Upendra Sharma Jul 25 '17 at 16:08
  • Actually, you created a global variable in `JavaScript`. You are already using it globally. The only use of jQuery in your code is making an `asynchronous` call that, _when successful_ (hint), assigns a value to your variable. – chazsolo Jul 25 '17 at 16:09
  • i want to use response globally. – Upendra Sharma Jul 25 '17 at 16:10
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – freedomn-m Jul 25 '17 at 16:22

1 Answers1

0

You should use async : false in ajax request