-2

My alert shows an "Undefined" with the following code:

var nonce = (function () {
$.ajax({
url: site_url + '/api/get_nonce/?controller=user&method=register&apikey=XXX&callback=?',
type: "GET",
dataType: 'json',
success: function(data){

nonce = data.nonce;
    }
});
return nonce;
})(); 

alert(nonce);

The JSON is:

?({"status":"ok","controller":"user","method":"register","nonce":"XXX"})

What I'm doing wrong?

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
desmeit
  • 550
  • 1
  • 7
  • 24

1 Answers1

2

Ajax calls are asynchronous. At the point you are doing the return nonce; the result hasn't arrived yet - or at least isn't guaranteed to.

You'd need to put the alert(nonce);, and anything else you want to do with the result, inside the success handler of the Ajax call.

In the long run, you also want an error callback to handle when something goes wrong.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • Okay thanks. But how is it possible to get the result of an ajax call and use in a variable (outside of the success handler)? I tried with an callback but then I can use it only in a function (another) again. – desmeit Jan 14 '16 at 09:41
  • @Maddin Possible, kindly see the dupe again. – Praveen Kumar Purushothaman Jan 14 '16 at 09:47
  • @Maddin `I tried with an callback but then I can use it only in a function (another) again.` that's kind of how JavaScript works I'm afraid. It's a different paradigm. You can force the Ajax call to be synchronous but that's not a good idea. – Pekka Jan 14 '16 at 09:49
  • 1
    I solved it within a function. Sorry that was a bit stupid :-D – desmeit Jan 14 '16 at 10:00