My boss has tasked me with adding some Javascript to a couple of pages to the website we're developing. I'm a total Javascript noob (I'm a PHP coder at heart), but I've been learning and using Javascript for two days and until now, everything was going pretty smoothly.
Now I'm running into a problem. I think it's related to variable scope, and I thought I understood variable scope, but I'm struggling with this very (probably) very simple task. If I had more time to learn how to use JS, I'd bang my head against it some more before coming to you folks, but I need something workable by next Monday. I'm close..
Code is below, explanation further below.
var activeTopic;
$.post("test.php",
{
request:"getActiveSection",
courseid:courseid
},
function (data, status) {
if (data != "none") {
activeTopic = data;
displayActiveTopic();
}
});
alert(activeTopic);
I'm using Jquery's POST function to make a call to test.php. PHP takes the course ID and returns the currently active topic. The PHP code is returning the correct value. I know this, because if I alert(data);, the correct value is displayed.
However, if I alert(activeTopic); outside the function, I notice the global variable activeTopic hasn't changed. Why?
Thanks in advance for the help. When I have some time, I'm going to put a bunch more effort into learning JS. It's a lot of fun so far... very different from PHP, but fun nonetheless.
2 Answers 2
This has nothing to do with scope and everything to do with timing.
- You declare a variable
activeTopic. - You send an HTTP (post) request
- You alert
activeTopic
Later, when the HTTP response arrives, a value is assigned to activeTopic.
You need to deal with the data inside the callback function that currently assigns a value to activeTopic.
1 Comment
$.post is an asynchronous function. So while alert() is called, the post is still running. Put the alert into your callback function, which will be called when the post call has finished.
activeTopic