Passing PHP variable to javascript file

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

<?php
	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:

<?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>

Leave a Reply

Your email address will not be published. Required fields are marked *