0

I'm having a little trouble calling a PHP variable into a jQuery script. Basically, I run a few functions to determine if a user is logged in and, if so, store that as $loggedin=1. If a person that is on a page is NOT logged in, when a button is clicked I want them to be prompted to sign in (I'll obviously still ensure the user is ACTUALLY logged in on the server side before any processing of data). I searched around, and found the easiest way to get that information over to jQuery is to create the script as a PHP file so I can echo it into the script. Here is the high level code I'm using:

Call up the script:

<?php
 $loggedIn = 1;
 <script src="../buttonScript.php"></script>
?>

Script:

<?php header("Content-type: application/javascript"); ?>
var buttonScript = function(){
 var loggedIn = <?php if($loggedIn===1){echo "1";}else{echo "0";} ?>;
  $("#button").click(function(){
  alert(loggedIn);
 });
};

$(document).ready(buttonScript);

When I click the button in a situation where $loggedIn is equal to 1, the alert gives me 0. In fact, if I simply echo $loggedIn in the script itself, the value is completely empty and the script errors out and won't pop up an alert at all. I'm confident that the PHP variable $loggedIn actually has a variable, since if I echo the variable right before the script is called, I successfully see the number 1. What am I missing here?

Note: added a couple lines in the script calling just for clarity.

12
  • What error are you seeing? Commented Sep 16, 2014 at 4:23
  • how do you assign a value to $loggedIn? Without that code the question is incomplete. Commented Sep 16, 2014 at 4:23
  • 1
    A file like buttonScript.php won't get interpreted by the Javascript engine? Commented Sep 16, 2014 at 4:24
  • seems right, open the file url in browser and see if output is as expected Commented Sep 16, 2014 at 4:38
  • 1
    Try setting $loggedIn to a session variable from that other page, and using the session variable there. If it works, then it should be a variable scoping issue. Commented Sep 16, 2014 at 4:46

1 Answer 1

1

Try this

<?php
 $loggedIn = 1;
 require("/path/buttonScript.php");
?>

buttonScript.php

<script type="text/javascript">
 var buttonScript = function(){
 var loggedIn = <?php echo $loggedIn; ?>;
  $("#button").click(function(){
  alert(loggedIn);
 });
};

$(document).ready(buttonScript);
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.