0

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?

cssyphus
  • 37,875
  • 18
  • 96
  • 111

2 Answers2

0

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.

Joe T
  • 2,300
  • 1
  • 19
  • 31
  • Yes, php runs first, but as far as the interpreter is concerned, the javascript he wrote is markup, so it would go ahead and process the php inside that markup. As long as his `$logged_in` var value is present on the server, the javascript should run as intended. It's more likely an issue of formatting... or he's not running that file as a php file. – Brian Vanderbusch Nov 26 '13 at 03:12
  • Thanks for the great explanation. Before I re-code using ajax, I have one question: if the php has set a variable at page load (and the value/variable has already been set), then why is that PHP variable not accessible at any point? – cssyphus Nov 26 '13 at 03:16
  • @BrianVanderbusch You've said what I thought myself. The $logged_in var *is* present on the server, and the file is a .php file (and all the other PHP things inside it work). However, the js is in an external file included via ` – cssyphus Nov 26 '13 at 03:18
  • 1
    if you have *any* server side code or tags on your page, that page has to be saved as a server side page, in this case being .php. If your index.js file is the file with the code above... then yes, that is absolutely the problem. – Brian Vanderbusch Nov 26 '13 at 03:22
0

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:

  1. Store logged-in value in a super-global: e.g. $_SESSION['logged-in'], or

  2. 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.

Simple explanation of AJAX and how it works

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111