Search code examples
javascriptvariablesscopescript-tag

JS variable scope and script sources


I have a variable defined in script tags within the head of the document:

<?php if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true) {
    echo '<script>var userdir = '.$_SESSION['user']->directory.'</script>';
} ?>

after that I include several javascript files, one of which includes a function which includes

if (type == 'image'){
   var imgElement = elementId.replace(/upload_/, "img_");
   $('#'+imgElement).attr("src", "assets/uploads/"+ userdir +"/images/" + vidfile);
}

userdir is defined within the document if I view source, but the image path that comes back is 'undefined'. shouldn't it be getting the value?


Solution

  • You almost certainly need to include quotes around the assignment to userdir.

    echo '<script>var userdir = "'.$_SESSION['user']->directory.'";</script>';