user1341521
user1341521

Reputation: 59

How to assign PHP expression to a JavaScript variable?

I know it seems like a daft question but I am getting synatx error var imagename = ;. in the code below.

 var imagename = <?php if (isset($_SESSION['imagename'])) echo json_encode($_SESSION['imagename']); ?>;

var imagename is a javascript variable but why am I getting this error? is it because ; is in the wrong place or am I messing a ; or have I added to many ;. I just can't seem to figure it out.

Thanks

Upvotes: 1

Views: 116

Answers (3)

user212218
user212218

Reputation:

Perhaps you are looking for something like this:

var imagename = <?php echo json_encode(isset($_SESSION['imagename']) ? $_SESSION['imagename'] : null); ?>

See http://php.net/ternary#language.operators.comparison.ternary for more info on how the ternary operator works.

Upvotes: 2

Marc B
Marc B

Reputation: 360782

You have no else clause, so if that session variable isn't set, you end up generating your empty assignment.

var imagename = <?php if (isset($_SESSION['imagename'])) { echo json_encode($_SESSION['imagename']); } else { echo "''"; } ?>;

Upvotes: 2

Will
Will

Reputation: 20235

The error is probably occuring when $_SESSION['imagename'] does not exist. You should add an else clause for when this happens.

Upvotes: 0

Related Questions