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?

2
  • You want to use it in another function? Commented Feb 12, 2013 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. Commented Feb 12, 2013 at 15:30

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah! Duh. Thanks. I'll accept your answer when StackOverflow lets me.
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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.