1

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.

  • It is not variable scope you are having an issue with. It's AJAX. – James Montagne Jan 31 '13 at 16:03
  • this is asynchronous meaning it's happening in parallel the rest of your code. usa a callback function instead and have the callback assign the value to `activeTopic ` – zero Jan 31 '13 at 16:03
  • Maybe this will help you as you advance further with Ajax: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call-from-a-function. – Felix Kling Jan 31 '13 at 16:11

2 Answers2

5

This has nothing to do with scope and everything to do with timing.

  1. You declare a variable activeTopic.
  2. You send an HTTP (post) request
  3. 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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
4

$.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.

Ilyssis
  • 4,849
  • 7
  • 24
  • 30