JavaScript Code and PHP
JavaScript Code and PHP
PHP code is executed on the server side and output data are transmitted to Web browser. JavaScript script code is executed by the browser on user's computer. Combining these two web programming languages, JavaScript scripts can achieve dynamic results based on data received and processed by the server. Thus, the same web page can contain a JavaScript code for a user and other JS code for another user. - There are two ways to combine PHP with JavaScript to achieve a dynamic and personalized result: 1) By writing the entire JS script within PHP code and adding it to the web page with PHP function "echo" (or "print").
<?php echo '<script type="text/javascript"> // JS code ... </script>'; ?>
- The string returned by 'echo' must be a JS code with correct syntax. 2) By adding in the JS script within the HTML document only the necessary data processed by PHP.
<script type="text/javascript"> var var_js = <?php echo $var_php; ?>; </script>
Both versions must be written into .php files that can be processed by the PHP module.
Or the second way: <?php session_start(); ?> <!-- HTML code --> <script type="text/javascript"> alert("Welcome <?php echo $_SESSION['nume']; ?>"); </script>
var secunde = serverdate.getSeconds(); // function that process and display data function ceas() { secunde++; if (secunde>59) { secunde = 0; minute++; } if (minute>59) { minute = 0; ore++; } if (ore>23) { ore = 0; }
// seconds
var output = "<font size='4'><b><font size='1'>Ora server</font><br />"+ore+":"+minute+":"+secunde+"</b></font>" document.getElementById("tag_ora").innerHTML = output; } // call the function when page is loaded and then at every second window.onload = function(){ setInterval("ceas()", 1000); } --></script>
b) In the same folder on the server create a html file (ex. "test_jsphp.html") where you add the fallowing code:
<script type="text/javascript" src="phpjs_test.php?id=2"></script>
- Call this html file on the server. The result will be a link (written by "document.write()") defined in php script, based on the 'id' added in the URL in "src" attribute.