1

I have the following function:

function loginStudent() {
    var advisorKEY = "<dtml-var expr="py_get_alias()">";
    var studentKEY = "<dtml-var SID>";  
    var URL = "py_logging_sessionOpen?AdvisorKEY=" + advisorKEY + "&StudentKEY=" + studentKEY;
    key = "";
    $j.get(URL, function(data) { 
        key = data;
    });
    alert(key);
}

The py_loggin_sessionOpen is just a python script running on my server.
It returns a single string. I need the response of that script to determine the next action. The script returns the value perfectly, and I can easily check the value by putting an alert within the function(data) in get.

My main question is: how to get the key value to be changed outside the scope of function(data)?

I assumed because I defined it externally it would act as a global variable. Moving it outside loginStudent() does not solve the problem either.

Any ideas?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Nathan Tornquist
  • 6,468
  • 10
  • 47
  • 72
  • You want to use it in another function? – Bhushan Firake Feb 12 '13 at 15:29
  • 4
    All logic which depends on the result of an asynchronous request must be dealt with in the callback function of the request. `alert(key)` is being called before the value of `key` is set by the async. function. – Rory McCrossan Feb 12 '13 at 15:30

2 Answers2

6

$j.get() is going to be an asynchronous call. That means it fires, and the rest of the execution continues. Anything that relies on that call needs to be done in the callback, like so:

$j.get(URL, function(data) { 
    key = data;
    alert(key);
} );

If everything else is good, you'll see the value you expect.

David Kiger
  • 1,958
  • 1
  • 16
  • 25
0

The problem with your code is that $j.get executes asynchronously. That's the reason you pass a callback to it.

If you wish to write asynchronous code synchronously then you should read this answer: https://stackoverflow.com/a/14809354/783743

Edit: It seems that you have created a global variable called key by not declaring it with var. Hence it should be visible in other functions as long as they are called after the callback.

Would you care to provide us these other functions?

Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299