2

What is the best way to pass a server-side PHP variable to Javascript?

To simplify the problem assume that we have a variable in PHP ($phpVar) and we want to assign its value to a Javascript variable (jsVar)

Javascript files are loaded in html - they are not created dynamic!

Some food for thought:

1. Print with PHP before loading Javascript files:

    <script language="javascript" type="text/javascript">
       var jsVar= <?php echo $phpVar?>;
    </script>

2. Store in DOM (in hidden elements)

a. in PHP:

    <span data-name="phpVar" data-value="<?php echo $phpVar?>"></span>

b. Read in Javascript files (assuming jQuery available):

    var jsVar= $('span[data-name="phpVar"]').attr('data-value');

3. Ask it with AJAX after page has loaded

Obviosly not the best solution. Doesn't fit to all scenarios and requires an additional request...

In conclusion:

  • They both seem ugly to me... Is there a better approach?
  • Is there any frameworks that can handle this dependecies? Please keep server reconfiguration minimal.
igaster
  • 12,983
  • 6
  • 26
  • 27
  • Solution 1 if the value does not depend dinamically from user interaction, solution 3 otherwise. Why don't you like them? – dirluca Feb 21 '14 at 10:03
  • AJAX is the best way, in what scenario do you think, ajax is not good? – Shaik Mahaboob Basha Feb 21 '14 at 10:03
  • 1
    @ShaikMahaboobBasha For AJAX you need to send a new subrequest to the server, that isn't a best solution. The best solution is a first case, you don't need to load server with subrequest. – Victor Bocharsky Feb 21 '14 at 10:07
  • Option 1 with `json_encode()` ... – Daniel W. Feb 21 '14 at 10:07
  • @DanFromGermany It better to use if you need to pass many variables – Victor Bocharsky Feb 21 '14 at 10:08
  • @Victor Yep, I agree with you, but its more elegant way to fetch the data and it has lot more benefits. – Shaik Mahaboob Basha Feb 21 '14 at 10:15
  • @ShaikMahaboobBasha First case is simple and quick. I think that `json_encode()` is also good idea for this. But what more benefits of AJAX do you mean, for example? – Victor Bocharsky Feb 21 '14 at 10:18
  • @Victor How many values you are going to fetch like these, and how much processing time it takes at back-end. In Modern Single page applications, we minimize initial loading time (processing time at back-end) and fetch the remaining data dynamically using AJAX. Ofcourse we are generating a new request but this is better than increasing the server processing by generating a large content at a time. – Shaik Mahaboob Basha Feb 21 '14 at 10:22
  • @ShaikMahaboobBasha Do you know that the time of this variable generating on page generation will be more quickly that generate it value with AJAX subrequest? And it get less load on the server, espacially when you use some PHP framework, which was init on the AJAX subrequest second time ) – Victor Bocharsky Feb 21 '14 at 10:34
  • @Victor If it is only just one variable, then its ok, but how many projects are like this. In our common requirements, we have more than a few configuration variables, we need to pass complex object, considering that too if you say AJAX is not recommended, I don't have any thing left to say. But in most scenarios AJAX suits the requirement and its jut takes milli seconds for the server to serve the AJAX request, of course it depends on the server and the database time spent, and network time. – Shaik Mahaboob Basha Feb 21 '14 at 10:50

2 Answers2

2

The best approach would be providing an "internal API" requested via AJAX from client side. Doing this way you can keep your sides separated.

After this, the fastest way is printing in a shared file the values you want to share (as you wrote in your question).

As a last note: if you carry on with the second way I would suggest you

json_encode()

as a really helpful method to pass arrays and objects from php to javascript.

So if you have your php array:

$array = array( "a" => 1, "b" => 2 );

<script language="javascript" type="text/javascript">
    var js_array= <?php echo json_encode( $array ) ; ?>;
</script>
Stefano Ortisi
  • 5,288
  • 3
  • 33
  • 41
  • That is what offered by @DanFromGermany – Victor Bocharsky Feb 21 '14 at 10:20
  • @Victor Who? I just wrote what I know it's the best. I don't know if someone else already offered it. Can you provide us with his answer? Thanks. – Stefano Ortisi Feb 21 '14 at 10:22
  • You can read the [comments](http://stackoverflow.com/questions/21930987/pass-server-side-variables-to-javascript-in-php#comment33219972_21930987) :) – Victor Bocharsky Feb 21 '14 at 10:27
  • 1
    Oh now i see, but he wrote the comment a couple of minutes after my answer. By the way, I don't really mind. The most important thing is that we gave @igaster the clearest idea of what's the best to do. Thank you! – Stefano Ortisi Feb 21 '14 at 10:31
1

It depends on the situation, but in common, predominantly to use first case. But don't forget about quotes if you pass a string:

<script language="javascript" type="text/javascript">
    var jsVar = '<?php echo $phpVar?>';
</script>
Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91