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”]
header("content-type: application/x-javascript");
$base_url = $_REQUEST[‘base_url’];
document.ready = function(e){
alert(‘<?php echo $base_url?>’);

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”]
$base_url = $_SERVER[‘HTTP_HOST’];
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="">
<script type="text/javascript" src="js.php?base_url=<?php echo $base_url?>"></script>


Leave a Reply

Avatar placeholder