3

I have a js function that make some ajax post and a php handler that parse the $_POST and do something. I would use in js and php the same constants. For example if i put some define in php:

define('done','1',TRUE);

I would like to have it on js too. Are there some way to have some constants declared one time and usable in all this 2 languages?

jedi
  • 839
  • 12
  • 33
  • You could make a PHP-generated JS file that redefines them. – SLaks Nov 01 '13 at 12:59
  • use AJAX to get it done.Send request to server and intialize your variable there to use it on client side. – Naeem Nov 01 '13 at 13:00
  • Found an [example](http://stackoverflow.com/questions/9696980/php-constant-inside-js-file) of "SLaks'method" – jedi Nov 01 '13 at 14:05

2 Answers2

4

Define your constants in PHP but output them to your javascript by either writing them to an index.php master file (or similar) or fetch them by ajax

Use get_defined_constants to retrieve all constants and parse that to json

ie (I am without environment at the moment and unable to test this)

<script type="text/javascript">
var constants = <?php echo json_encode(get_defined_constants()); ?>
</script>

Have a look at the documentation on get_defined_constants how to retrieve your personal constants, http://php.net/manual/en/function.get-defined-constants.php

Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157
  • I wouldn't advise that solution due to security reasons. A whitelist is definitely better. – ComFreek Nov 01 '13 at 13:04
  • 1
    @ComFreek I agree but get_defined_constants can also retrieve user defined constants. Hence the security lays in what the developer adds to that context. But in general you are right, even though thats not what op asked for :) – Eric Herlitz Nov 01 '13 at 13:06
  • I understad the security reason but i'm not sure of what you are talking whit "whitelist". Can you make an example to complete the question whit a better answer? – jedi Nov 01 '13 at 13:24
0

You could write your js in a PHP file and use your function returns echo'd out in your javascript i.e.

<?php 
$someid = 'wrapper';
?>
<script type="text/javascript">
document.getElementById("<?php echo $someid; ?>");
</script>
ggdx
  • 3,024
  • 4
  • 32
  • 48