redstang423
redstang423

Reputation: 133

PHP variable is empty when called in jQuery script

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.

Upvotes: 0

Views: 412

Answers (1)

Himal
Himal

Reputation: 1371

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>

Upvotes: 1

Related Questions