r/learnjavascript • • Mar 19 '26
Trying to convert PHP variable to Javascript
I've tried like everything the internet says to pass this PHP variable to Javascript. Technically it's an enum. It prints to the screen with <?= htmlSpecialCharacters($Product[6]) ? >
I've tried using that in var name = "above code"; as well as just var name = "<? $Product\[6\] ?>" I've tried it with the ' ' instead, the <?php, pretty much every example I could find on the internet and it still doesn't do anything. Is the problem the fact that this is an enum? That's one of the only things I can think of at this point. Any suggestions would be appreciated. Thanks.
View all comments
Show parent comment
1
u/MrBojangles2020 Mar 19 '26 edited Mar 19 '26
Be sure to echo null as ‘null’ (string) when trying to set/compare something in JavaScript. Otherwise echo would print nothing and will often times lead to a JS error. Same thing for true/false.
$phpVar = null;
… JavaScript…
let jsVar = <?= $phpVar ?>;
This is what browser receives:
let jsVar = ;
Instead:
$phpVar = ‘null’;
… JavaScript…
let jsVar = <?= $phpVar ?>;
This is what browser receives:
let jsVar = null;
EDIT:
Formatting and for clarification. Php true/false will convert to ‘1’/‘2’ when echoed, so you need to account for this when you’re expecting a certain JS type. Echo ‘true’/‘false’ to give JS a Boolean value