-1

I have a simple script to get a PHP session user id into a javascript file. Yet when I try to simply alert the user id it says undefined?

As shown in code I have tried with simple alert to check the data coming back from the script and it is correct.

var user_id;

$.get( "/ajax/actions/getUserId.php", function( data ) {

    // alert(data); <-- this works correctly

    var user_id = data;

});

alert(user_id);

Is there a better way to do this?

The PHP file accessed (getUserId.php) is simply:

session_start();

echo $_SESSION[user_id];
StudioTime
  • 22,603
  • 38
  • 120
  • 207

2 Answers2

2

You should use:

$.get( "/ajax/actions/getUserId.php", function( data ) {    
    var user_id = data;
    alert(user_id);
});

Ajax is asynchronous by default.

In your snippet the code goes through the following steps:

  1. Define variable called user_id in the global lexical scope
  2. Make GET ajax request to /ajax/actions/getUserId.php
  3. Alert the value of the variable user_id which is undefined (by default, you haven't set it any value).
  4. At given point the ajax request is successfully completed, your callback gets invoked so:
    1. You define new variable called user_id, in the lexical scope of your callback
Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
  • Thanks, so can I not use the variable user_id outside the ajax call? I was using the alert AFTER the call as I need the variable further down the js file - or in English, can I make the ajax call happen before the file loads? – StudioTime Feb 06 '14 at 17:07
  • I included extra explanation, you can review it. – Minko Gechev Feb 06 '14 at 17:08
  • @DarrenSweeney you can leave only the second variable declaration - the one in the ajax callback. – Minko Gechev Feb 06 '14 at 17:09
2

Ajax is asynchronous, so the last alert will be executed before the callback function of ajax is called.

Subash Selvaraj
  • 3,385
  • 1
  • 14
  • 17