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:
echo
' (or 'print
').
<?php echo '<script> var str ="JS code"; </script>'; ?>- The string returned by 'echo' must be a JS code with correct syntax.
<script> var var_js = '<?php echo $var_php; ?>'; </script>• Both versions must be written into .php files that can be processed by the PHP module.
$_SESSION['username']
).<?php session_start(); // ... php code ... echo "<script>alert('Welcome ". $_SESSION['username'] ."');</script>"; ?>
<?php session_start(); ?> <!-- HTML code --> <script> alert('Welcome <?php echo $_SESSION["username"]; ?>'); </script>
<div id='tag_ora'></div> <script> // Clock script server-time, https://coursesweb.net // use php to get the server time var dt_serv = new Date(<?php echo date('y,n,j,G,i,s'); ?>); var ore = dt_serv.getHours(); //hour var minute = dt_serv.getMinutes(); //minutes var secunde = dt_serv.getSeconds(); //seconds // function that process and display data function jsClock(){ secunde++; if(secunde>59){ secunde = 0; minute++; } if(minute>59){ minute = 0; ore++; } if(ore>23) ore = 0; var output ='<h4>Server time - '+ore+':'+minute+':'+secunde+'</h4>'; document.getElementById('tag_ora').innerHTML = output; } //calls the function every second setInterval('jsClock()', 1000); </script>- Test it yourself, in a .php file, on the server.
$_GET
to get the parameters from the received URL. According to those parameters, the PHP processes data on the server and return a HTML and JavaScript code that can display in your page what they want, the traffic site, a banner, ....<?php $ids =[1=>'php-mysql', 2=>'javascript', 3=>'html']; // gets the id from URL if(isset($_GET['id'])){ if($str = $ids[$_GET['id']]){ //return a string with a JS instruction that will display a link echo 'document.write("<a href=\'https://coursesweb.net/'. $str. '\'>Course '. $str. '</a>");'; } } ?>
<script src='phpjs_test.php?id=2'></script>
document.write()
) defined in php script, based on the 'id' added in the URL in 'src' attribute.
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net