I have a php ternary operator as follows that does not work:
var newLoginTxt = <?=$_SESSION['loginStatus']? 'Logged in' : 'Login'?>;
alert("About to set the navbar's login text to: " + newLoginTxt);
No alert box appears at all.
However this does work:
var curLoginStatusSessionVar = <?=$_SESSION['loginStatus']? 'true' : 'false'?>;
alert("Testing: " + curLoginStatusSessionVar);
The alert box appears and says “Testing: false”
I have the following article seeming to say that the ternary operator in php CAN in fact return values other than ‘true’ or ‘false’:
http://davidwalsh.name/php-shorthand-if-else-ternary-operators
Okay, even more odd — in the code below, why does the first “Testing” alert box appear, then the 2nd “Testing” alert box NOT appear? It’s the exact same code:
// THIS "Testing" ALERT BOX APPEARS FINE**
var curLoginStatusSessionVar = <?=$_SESSION['loginStatus']? 'true' : "false"?>;
alert("Testing: " + curLoginStatusSessionVar);
var newLoginTxt = <?=$_SESSION['loginStatus']? 'Logged in' : 'Login'?>;
alert("About to set the navbar's login text to: " + newLoginTxt);
// THIS IDENTICAL "Testing" ALERT BOX NEVER APPEARS**
curLoginStatusSessionVar = <?=$_SESSION['loginStatus']? 'true' : 'false'?>;
alert("Testing" + curLoginStatusSessionVar);
Your problem is completely unrelated to the ternary expression: In JavaScript, like in modern php, strings must be encapsulated by quotes.
true and false happen to be JavaScript constants. Therefore, you want:
Alternatively, and if the data is more complicated, use
json_encode. For example, if you want to access the value of a php variable$title(which could contain quotes) in JavaScript: