0

I've a variable in my Javascript inside _.php_ file. Is it possible to send that variable into a external JavaScript file?

This is the JavaScript inside my php:

<?php
$point = floor($countData / 4);
$percent = 0;
for ($k = $j; $k < $countData; $k++) {
    if ($k % $point == 0 && $k > 0) {
        $percent = $percent + 10;
        ?> 
        <script type="text/javascript">
        var percents = <?php echo $percent; ?>;
        </script>
    <?php 
    }
}
?>

Is it possible to send the var percents above into an external JavaScript called _upload.js_ file?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Blackjack
  • 1,016
  • 1
  • 20
  • 51
  • Can you edit your question to clarify what you mean by "send the var percents to upload.js file"? Also what is upload.js? – Grisha Levit Jan 15 '17 at 20:38
  • @GrishaLevit thanks for the suggestion. The question has been updated – Blackjack Jan 16 '17 at 03:28
  • I don't get it, if you have only a variable named `percents`, why are you assigning value to it in a `for loop`? It does not make any sense. Because `percents` will always contain the last value you have assigned to it! And the answer to your question may be yes, depending on what you have in your _upload.js_ file... – EhsanT Jan 16 '17 at 04:45
  • Possible duplicate of [How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – Martijn Jan 17 '17 at 16:25

3 Answers3

0

It is possible because it will generate the page content which will be later interpreted by the browser.

Michał Pietraszko
  • 5,666
  • 3
  • 21
  • 27
0

The best way send data from server to javascript is use AJAX.
Good answer you can read here stackoverflow

Community
  • 1
  • 1
Alex K.
  • 18
  • 2
0

Yes you can, however how depends on how your external js file works. You could just do it like this:

<?php
    $point = floor($countData / 4);
    $percent = 0;
    for ($k = $j; $k < $countData; $k++) {
        if ($k % $point == 0 && $k > 0) {
            $percent = $percent + 10;
        }
    }
?>

<script type="text/javascript">
    var percents = <?= $percent ?>;
</script>

This way you just echo the value of $percent and assign it to var percents.

However how that value is then used by the external js file we don't know.

  • The external js file could directly make reference to var percents in which case you will want to make sure your script runs before the external js file.

  • Another way might be for the external js file to have a method you can call to pass the value and let the external js begin doing it's job. In which case you will want to have your script execute after the external js file.

marche
  • 1,756
  • 1
  • 14
  • 24