how can we use php in between javascript ?????
like
function jst()
{
var i = 0 ;
i = <?php echo 35; ?>
alert( i );
}
Please suggest a better way
how can we use php in between javascript ?????
like
function jst()
{
var i = 0 ;
i = <?php echo 35; ?>
alert( i );
}
Please suggest a better way
Yes, you can, provided your JavaScript code is embedded into a PHP file.
You're pretty much on the ball. The only difference is I'd separate out the javascript 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 js - on client.
However we can generate JS code as well as HTML, using all PHP features, including escaping from HTML one
If your whole JS 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 what you can do is just pass variables around in JS. 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 JS files. This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serializing them into a format that JS can use.
If you put your javascript code in php file, you can 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 );
}