从PHP获取变量设置Javascript变量

I have a page which I have collected two variables, I want to pass these variables to my document ready function. but for some reason.. My alerts for testing are just outputting the line code rather than the result.

just to note the JS script is in another file which is linked to the page.

PHP

<?php 

$cardid = test;
$custid = test;

?>

Javascript

$(document).ready(function(){

   var custid = '<?php echo($custid); ?>';
   var cardid = '<?php echo($cardid); ?>';

   alert(custid);
   alert(cardid);
});

Put your javascript code into a separate php file under script tag:

<script>

    $(document).ready(function(){

       var custid = '<?php echo($custid); ?>';
       var cardid = '<?php echo($cardid); ?>';

       alert(custid);
       alert(cardid);
   })

</script>

Include this file in your main php file (using the include function). It is not possible to execute php in a separate .js file.

you aren't assigning anything to your PHP variables:

$cardid = test;
$custid = test;

a value which isn't numeric and isn't in between quotation marks is considered a constant in PHP. and the constant test most likely has no value in your PHP environment.

you wanted to assign a string, i guess, so don't forget the quotation marks:

$cardid = "test";
$custid = "test";

Wrong concept. Your JS is not parsed by PHP, so your approach will not work. Lets make it work:

You have to give the Variables to JS with one trick: Write it into the HTML in a script-tag, then you can access them in your JS.

Lets assume, you produce a HTML like this in your PHP:

<body>
 <div>Hello World</div>
</body>

Now, write the variables for you JS into it, here is a simple approach:

echo "<script>var myVar1='".$_GET['var1']."';</script>
";
echo "<body>
";
echo "  <div>Hello World</div>
";
echo "</body>
";

Okay, very simple, do not do it like this in real, but you got the concept? So, that was the trick to do this.

P.S. The same way, you get $_POST Data to your JS ;)

Consider using quote to represent string.

<?php 

$cardid = 'test';
$custid = 'test';

?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.js"></script>
<script>
$(document).ready(function(){

   var custid = '<?php echo($custid); ?>';
   var cardid = '<?php echo($cardid); ?>';

   alert(custid);
   alert(cardid);
});
</script>

PHP code will only be run in files ending with .php. Your.js file is loaded directly and not subject to PHP processing. If you wish to assign values from PHP variables to javascript variables you will need to do so in a script block in your .php file.

For example if you add this to your .php file -

<script type="javascript">
  var custid = '<?php echo $custid; ?>';
  var cardid = '<?php echo $cardid; ?>';
</script>

Then in your .js file shold look like -

$(document).ready(function(){
   alert(custid);
   alert(cardid);
});