December 18, 201213 yr So i need to get the value of a php variable inside a javascript function that updates a div with content when called. Now i know u can just pass the variable as a parameter in the function but i thought as a global solution i would do this <?php if($pid){?> <script> var pid = <?php echo $pid;?>; </script> <?php }else{?> <script> var pid = ''; </script> <?php }?> and then i can use the value of pid in my ajax request within a seperate external javascript file. Is this an ok way to do this?
December 19, 201213 yr Not really sure why you have duplicated the script or indeed the JS code... You would be better using <script> var pid = <?php echo $pid ? $pid : "''"; ?> </script> That said, personally I would put any js variables into an array in php, then use json_encode() and set one variable to have all the array values in, such as <?php $vars = array( 'pid' => $pid ); ?> <script> var v = <?php echo json_encode($vars); ?>; </script> Then to call the variable for $pid in JS, you could just use v.pid This is a more convoluted method for the single variable, but if you're passing multiple, this becomes far more convenient and means you don't have to assign loads of variables in JS Edited December 19, 201213 yr by Jay Gilford
December 19, 201213 yr Author Not really sure why you have duplicated the script or indeed the JS code... You would be better using <script> var pid = <?php echo $pid ? $pid : "''"; ?> </script> That said, personally I would put any js variables into an array in php, then use json_encode() and set one variable to have all the array values in, such as <?php $vars = array( 'pid' => $pid ); ?> <script> var v = <?php echo json_encode($vars); ?> </script> Then to call the variable for $pid in JS, you could just use v.pid This is a more convoluted method for the single variable, but if you're passing multiple, this becomes far more convenient and means you don't have to assign loads of variables in JS thank you your way does make more since ill try that
December 28, 201213 yr Remember that PHP is a server-side scripting language, and Javascript resides on a client's browser. So, you could actually... Write directly any java-script you wish from your PHP script.
Create an account or sign in to comment