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?

3
  • You could make a PHP-generated JS file that redefines them. Commented Nov 1, 2013 at 12:59
  • use AJAX to get it done.Send request to server and intialize your variable there to use it on client side. Commented Nov 1, 2013 at 13:00
  • Found an example of "SLaks'method" Commented Nov 1, 2013 at 14:05

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

I wouldn't advise that solution due to security reasons. A whitelist is definitely better.
@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 :)
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?
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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.