How do I embed PHP code in JavaScript?

PhpJavascript

Php Problem Overview


How can we use PHP code in JavaScript?

Like

function jst()
{
    var i = 0;
    i = <?php echo 35; ?>
    alert(i);
}

Please suggest a better way.

Php Solutions


Solution 1 - Php

If your whole JavaScript code gets processed by PHP, then you can do it just like that.

If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.

For example, in your index.php (or wherever you specify your layout), you'd do something like this:

<script type="text/javascript">
    var my_var = <?php echo json_encode($my_var); ?>;
</script>

You could then use my_var in your JavaScript files.

This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.

Solution 2 - Php

If you put your JavaScript code in the PHP file, you can, but not otherwise. For example:

page.php (this will work)

function jst()
{
    var i = 0;
    i = <?php echo 35; ?>;
    alert(i);
}

page.js (this won't work)

function jst()
{
    var i = 0;
    i = <?php echo 35; ?>
    alert(i);
}

Solution 3 - Php

PHP has to be parsed on the server. JavaScript is working in the client's browser.

Having PHP code in a .js file will not work, except you can tell the server to parse the file you want to have as .js before it sends it to the client. And telling the server is the easiest thing in the world: just add .php at the end of the filename.

So, you could name it javascript.php. Or, so you know what this file is PRIMARILY, you could name it javascript.js.php - the server will recognize it as .php and parse it.

Solution 4 - Php

This is the bit of code you need at the top of your JavaScript file:

<?php
    header('Content-Type: text/javascript; charset=UTF-8');
?>

(function() {
    alert("hello world");
}) ();

Solution 5 - Php

Yes, you can, provided your JavaScript code is embedded into a PHP file.

Solution 6 - Php

You're pretty much on the ball. The only difference is I'd separate out the JavaScript code so the majority was in an external static file. Then you just define variables or call a function from the actual PHP page:

<script type="text/javascript>
    function_in_other_file(<?php echo my_php_var; ?>);
</script>

Solution 7 - Php

A small demo may help you: In abc.php file:

<script type="text/javascript">
    $('<?php echo '#'.$selectCategory_row['subID']?>').on('switchChange.bootstrapSwitch', function(event, state) {
        postState(state,'<?php echo $selectCategory_row['subID']?>');
    });
</script>

  

Solution 8 - Php

Here is an example:

html_code +="<td>" +
            "<select name='[row"+count+"]' data-placeholder='Choose One...' class='chosen-select form-control' tabindex='2'>"+
                "<option selected='selected' disabled='disabled' value=''>Select Exam Name</option>"+
                "<?php foreach($NM_EXAM as $ky=>$row) {
                echo '<option value='."$row->EXAM_ID". '>' . $row->EXAM_NAME . '</option>';
               } ?>"+
            "</select>"+
        "</td>";

Or

echo '<option value=\"'.$row->EXAM_ID. '\">' . $row->EXAM_NAME . '</option>';

Solution 9 - Php

We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.

However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmit SharmaView Question on Stackoverflow
Solution 1 - Phpreko_tView Answer on Stackoverflow
Solution 2 - PhpSarfrazView Answer on Stackoverflow
Solution 3 - PhpNataschaView Answer on Stackoverflow
Solution 4 - PhpWilliam AuslingView Answer on Stackoverflow
Solution 5 - PhpPablo Santa CruzView Answer on Stackoverflow
Solution 6 - PhpOliView Answer on Stackoverflow
Solution 7 - PhpZhang EvanView Answer on Stackoverflow
Solution 8 - PhpBablu AhmedView Answer on Stackoverflow
Solution 9 - PhpYour Common SenseView Answer on Stackoverflow