0

I'm not new to js but there's a stupid problem with jquery get method that it can't change global variable and I don't know why?

function getData(data) {
    re=null;
    $.get("http://example.com/api.php",{ d:data}).done(function(result){

            re = true;

        }).fail(function(){

            re = false;

        });
        console.log(re);
        return re;
}

If you see the console it's still null !
Any ideas?

UPDATE :

My problem is not with console.log() , actually the problem is that I cant store and return value like this :

alert(getData(data));

This still returns null.

Alexander Jones
  • 103
  • 3
  • 11
  • This is because the `get` call is not finished when you call `console.log`. You have to put `console.log` in the `done` and in the `fail` callbacks. – ADreNaLiNe-DJ Feb 27 '18 at 09:54
  • 2
    ajax is asynchronous,you can console.log(re) in your done or fail callback – xianshenglu Feb 27 '18 at 09:54
  • @xianshenglu I want to return the value – Alexander Jones Feb 27 '18 at 09:55
  • You can't as the AJAX call is asynchronous. You'll need to use the callback pattern instead. See the duplicate I marked for more information – Rory McCrossan Feb 27 '18 at 10:01
  • @Rory McCrossan Thank you for your mention to another question but I think my problem is a bit different, I want to store the result of that `callback()` in a global variable like `re`. Can you help me with this or re-open the question to update it? – Alexander Jones Feb 27 '18 at 10:35
  • No, the problem is the same. You cannot do that with asynchronous code as you do not know when it completes and the value has been set. This is why you need to use the callback pattern. I'd suggest researching asynchronous logic flow if you're struggling to comprehend the issue. – Rory McCrossan Feb 27 '18 at 10:36

1 Answers1

1

This is because $.get is an asynchronous call and by the time re variable is reassigned a new value, console.log is getting executed.

You can use a callback function when calling your async function getData(data).

function getData(data,callback) {
$.get("http://example.com/api.php",{ d:data}).done(function(result){

        callback(true)

    }).fail(function(){

        callback(false);

    });
}
//call it with your data and callback function
getData(data, function(response){
     console.log(response); // this will contain true or false as returned from your getData function.
})

I hope this helps.

Farhan Haque
  • 991
  • 1
  • 9
  • 21