0

I want to use a php login name in my javascript game...

I have this at the top of my php page that runs the javascript:

<?php
$username = (isset($_GET['username']) ? ($_GET['username']) : "dude");
?>

In my javascript I have this... which doesn't alert the name at all and throws a Uncaught ReferenceError: daniel is not defined error:

var name = <?php echo $username; ?>;
alert(name);    

And then I have this... which displays the name correctly at the top of the HTML:

<?php  
  echo "Welcome back " . $username . "...";
?>

If the name is being displayed correctly server side when the page has loaded, why can't it be alerted out from the Javascript?

Thanks

0

2 Answers 2

2

You aren't delimiting the value as a JavaScript string. It may be a string on the server, but not on the client. Do the following:

Change this:

var name = <?php echo $username; ?>;

To this:

var name = "<?php echo $username; ?>";
Sign up to request clarification or add additional context in comments.

1 Comment

No worries dude, happens to all of us. ;)
1

Enclose your php code within quotes.Try like this :

<script type="text/javascript">
    var name = '<?php echo $username; ?>';
    alert(name);  
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.