0

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.

asked May 19, 2015 at 17:18
0

2 Answers 2

3

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.

answered May 19, 2015 at 17:20
Sign up to request clarification or add additional context in comments.

Comments

0
var session_username = "<?php echo $_SESSION['username']; ?>";

or

var session_username = <?php echo json_encode($_SESSION['username']); ?>;
answered May 19, 2015 at 17:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.