GregH GregH - 5 months ago 36
PHP Question

Include PHP inside JavaScript (.js) files

I have a JavaScript file (extension

.js
, not
.html
) containing several JavaScript functions.

I want to call one of the PHP functions in a PHP file containing only several PHP functions from within one of the JavaScript functions.


  • Is that possible?

  • Would I need to "include" the
    .php
    file containing the PHP function in the
    .js
    file?

  • How would I do that?
    For example, say I had a file called myLib.php containing a function called
    myFunc
    that takes two parameters (
    param1
    and
    param2
    ). Then I have a
    .js
    file containing a function called
    myJsFunc
    . How would a call the
    myFunc
    (PHP) from within the
    myJsFunc
    (JavaScript function)? Wouldn't I need to include the PHP file somehow in the
    .js
    file?


Answer

If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.

<script type="text/javascript">
    phpVars = new Array();
    <?php foreach($vars as $var) {
        echo 'phpVars.push("' . $var . '");';
    };
    ?>
</script>
<script type="text/javascript" src="yourScriptThatUsesPHPVars.js"></script>

If you're trying to call functions, then you can do this like this

<script type="text/javascript" src="YourFunctions.js"></script>
<script type="text/javascript">
    functionOne(<?php echo implode(', ', $arrayWithVars); ?>);
    functionTwo(<?php echo $moreVars; ?>, <?php echo $evenMoreVars; ?>);
</script>