GregH GregH - 1 year ago 247
PHP Question

Include PHP inside JavaScript (.js) files

I have a JavaScript file (extension

, not
) 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
    file containing the PHP function in the

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

Answer Source

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 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; ?>);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download