Reputation: 2851
I'm attempting to make a comments system, and their comment gets posted in a div on submit. I need to set their username:
var session_username = <?php echo $_SESSION['username']; ?>;
var full = '<div> ...' + session_username + '...</div>';
$('#commentslice').prepend(full);
In the console it's saying:
Uncaught ReferenceError: [whatever the username is] is not defined.
Upvotes: 0
Views: 671
Reputation:
var session_username = "<?php echo $_SESSION['username']; ?>";
or
var session_username = <?php echo json_encode($_SESSION['username']); ?>;
Upvotes: 0
Reputation: 48267
Unless your PHP value (presumably a string) contains its own quotes, you should wrap it:
var session_username = "<?php echo $_SESSION['username']; ?>";
Let's say the username is "foo" and you haven't wrapped it. The replacement will come out to:
var session_username = foo;
which is a reference to the variable foo
. If that's not defined (and usernames will likely be randomish strings that aren't in your code), you'll run into this error.
This won't change how the PHP behaves at all, it will still replace that snippet with the value of the session username. The JS, however, will see a string variable and treat it as a bit of text.
Upvotes: 3