[php] How do I embed PHP code in JavaScript?

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.

This question is related to php javascript

The answer is


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>';

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.


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);
}

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>

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.


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>

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


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");
}) ();