Embed php in javascript using PHP  echo command. This is very effective method to define PHP variables in Javascript code. The example below how to embed php in javascript.

embed php in Javascript

How to embed php in javascript

a). PHP “echo” command
<?php $id=10; ?>
<script type=”text/javascript”>
var test_id = <?php echo $id; ?>;

In this example, the PHP ‘echo’ is to print message to the output screen and value of the variable directly into the Javascript on the web page. It’s very important to note that PHP variables must always be preceded by a $. In the example above, the PHP script first creates the $id variable, and then assigns it the value of 10. The PHP echo command used the bracketed on both sides by a question mark and it is store in variable.

There are many method to embed php in javascript like passing variables in Javascript HREF (window.location.href=”), using command echo.
Most commonly used  method is Javascript and PHP is to pass Javascript variables to a PHP file by calling the PHP page within Javascript.

b). HREF call method.
<!– script file –>
<script type=”text/javascript”>
window.location.href = “http://localhost/test.php;
<!–  Php File (test.php) –>
<?php echo ‘<h1>This is href calling</h1>’;?>

Other method how to embed php in javascript using script function

<form action=”” method=”post” class=”How To Embed PHP In Javascript” id=”form_static” enctype=”multipart/form-data” onsubmit=”return validation();”>

//Use your code


<script language=”javascript” type=”text/javascript”>
function validation()

//Get the codeigniter url id in script

var cat_id=”<?php echo $this->uri->segment(‘4’); ?>”;


One more think remember before you embed php in javascript :- PHP script active on the server side (code is executed on the web server) and Javascript active on the browser (It runs on the user’s side after the page has been load from the server). PHP script cannot load if the browser has loaded your script since the javascript runs post PHP output.

Hello Friends its me "Turna" PageQueen founder. I am from India currently working and being a part time blogger. I love to make money online and also loves to blog. You can contact me for Web development Tricks, Web Designing, Blogging Tips, And Other Programming Stuff.