The jquery code:
$('.up_IMG').click(function() {
if (notLoggedIn()) return false;
alert('Got to here');
});
The function (attempt #1): in quotes:
function notLoggedIn() {
alert('here');
logged_in = "<?php echo json_encode($logged_in); ?>";
alert('Logged in: ' + logged_in);
}
OR json_encoded (attempt #2):
function notLoggedIn() {
alert('here');
logged_in = <?php echo json_encode($logged_in); ?>;
alert('Logged in: ' + logged_in);
}
When attempt #1 fn is called, the first code block's alert displays:
The second code block does nothing.
The PHP variable does exist and has the value zero.
Any thoughts as to what's happening?
If you're calling this code with a 'click', at that point it's too late for PHP to help you asynchronously.
PHP runs when the page is loaded, not after. It's a matter of timing. PHP can never output something that doesn't exist yet, so it will always be blank.
Explanation of Solution:
The question was caused by a misunderstanding of the relationship between PHP and javascript.
Once the page has rendered (that is, inside jQuery's $(document).ready()
), all PHP regular variables no longer exist. The PHP super-variables exist (such as $_SESSION
, but not $logged_in
.
To possible solutions:
Store logged-in value in a super-global: e.g. $_SESSION['logged-in']
, or
Use AJAX inside the javascript $(document).ready()
to query PHP if the user is logged in, and receive the answer in the AJAX function's success:
function.