PHP and Javascript work on different sides. PHP work on server side while Javascript work at client side. If your javascript file is separate from html file, you cannot refers to PHP variables. But there is a tricky way how to passing PHP variable into javascript file.
Write you Javascript file as PHP
[sourcecode lang=”javascript”]
<?php
header("content-type: application/x-javascript");
$base_url = $_REQUEST[‘base_url’];
?>
document.ready = function(e){
alert(‘<?php echo $base_url?>’);
}
[/sourcecode]
In the above code, you have read PHP variable in javascript file. Save above code as [cci]js.php[/cci]
Include javascript file in html head
This is simple [cci]index.php[/cci] file:
[sourcecode lang=”php”]
<?php
$base_url = $_SERVER[‘HTTP_HOST’];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="js.php?base_url=<?php echo $base_url?>"></script>
</head>
<body>
</body>
[/sourcecode]
0 Comments