Pages

PHP & Javascript

All the PHP code will execute on the server before the page is sent to the client, meaning all of the PHP calls have all been replaced by whatever text they returned once the JavaScript is able to execute.

<script>
document.write("<?php echo 'hello!'; ?>");
</script>
 
<?php 
echo "<script language=\"JavaScript\">"; 
echo "alert(\"Hello World\");"; 
echo "</script>"; 
?>
 

<?php $phpvar=1; ?>
<script type="text/javascript">
jsvar = 3;
//Assign jsvar javascript variable value to php variable $phpvar
'<?php $phpvar="<script>document.write(jsvar)</script>"; ?>';
</script>
<?php echo $phpvar; ?>
 
‘Loop’ Example
 
<script type="text/javascript">
var counter = 0;
for(i=0;i<10;i++){
counter++;
}
</script>

<?php 
$phpvar= "<script>document.write(counter)</script>"; 
echo $phpvar;
?>
 
‘Session’ Example

<?php session_start(); $_SESSION['nume']='Sanat';?>
<!-- HTML code -->
<script type="text/javascript">
alert("Welcome <?php echo $_SESSION['nume']; ?>");
</script>
 
‘Switch’ Example

<script type="text/javascript"> 
function test(){ 
 document.getElementById("php_code").innerHTML="<?php  
  $w="do"; 
  switch($w){ 
  case 'do': echo "You will be logged in?"; break; 
  case 'loguot': echo "You will be logged out?" ; break;
  } 
 ?>"; 
} 
</script> 

<a href="" onclick="test(); return false;"> test </a> <br>
<span id="php_code"> </span>
 
Pass the value within url.

<?php 
    if(isset($_GET[action])){
 // Retrieve the GET parameters and executes the function
   $funcName  = $_GET[action];
   $vars   = $_GET[vars];
   $funcName($vars); 
  } else if (isset($_POST[action])){
   // Retrieve the POST parameters and executes the function
   $funcName  = $_POST[action];
  $vars   = $_POST[vars];
  $funcName($vars);    
  } else {   
  echo "<INPUT NAME='click_me' TYPE='button' ONCLICK='javascript:javaFunction()' VALUE='Click Me'>";
  }
  
   function phpFunction($v1){
 // makes an array from the passed variable  
 // with explode you can make an array from string. 
 $varArray = explode(",", $v1); 
  
 echo "First Value: $varArray[0] <BR>";
 echo "Second Value: $varArray[1]<BR>"; 
   }
  ?> 
 
  <SCRIPT language="javascript">
   function javaFunction(){
 // In the varArray are all the variables you want to give with the function
 var varArray = new Array();
 varArray[0] = "Hello";
 varArray[1] = "World";
   
 // the url which you have to pass an action to the GET- or POST-variable
 var url="<?php echo $_SERVER[PHP_SELF];?>?action=phpFunction&vars="+varArray;
 
 // Opens the url in the same window
    window.open(url, "_self");
   }
  </SCRIPT>
Output :
First Value: Hello
Second Value: World

No comments:

Post a Comment