0

I'm trying to call an API and check to see if a username exists in a database. The API works perfectly and is returning the username correctly. The issue I am having is that I need to define some variables globally to use later.

$(document).ready(function() {
var deviceID = getUrlVariables()["me"];
$.ajax({
    url: "funcEntity.cfc?method=getUsername&returnformat=json",
    dataType: "json",
    data: {
        deviceID: deviceID
    },
    success: function(result) {
        if(result == 0){
            alert("Proceed to login menu.");
        }
        else{
            username = result;
        }
    }
});
alert(username);
});

The result of the API should be the username and should be able to use globally in other functions? Correct? However, I am getting an error saying the variable "username" is undefined.

Cory Fail
  • 1,070
  • 8
  • 26

1 Answers1

0

You'll have to wait till you get em

That is the problem.

Asynchronous in ajax is not synchronous

What you can do is place the relevant bit of code which uses the returned data from the server inside the success handler. Or have any callbacks

Community
  • 1
  • 1
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • That could be a lot of functions. What this is doing is checking to see if the user exists and grabbing the users information at the start of the application. – Cory Fail Mar 27 '14 at 15:24
  • you have no other go. But if you can invest your time in deferred objects and promises, then go ahead – Amit Joki Mar 27 '14 at 15:29