Passing JavaScript variables to PHP
by Sagar Awasthi on Oct.16, 2009, under Passing JavaScript variables to PHP
JavaScript is a client side scripting language, while PHP is a server side technology. Unlike other programming language i.e. Java or ASP.Net, PHP doesn’t have any plugin/tools to help it to work at client side. Byut we can combine Javascript and PHP to develp a High tech web applications.
Let’s take example of defining visitor’s screen resolution. We will be JavaScript to get screen resolution and then pass the same data to PHP. We’ll have two files then one is HTML JavaScript file(screen.html) and other for PHP(screen-res.php).
Here we go:
<!– screen.html–>
<HTML>:
<header>
<title>Passing Variables</title>
<script type=”text/javascript”>var scrwidth = screen.width;
var scrheight = screen.height;if (scrwidth > 0 && scrheight >0)
{
window.location.href = “http://localhost/prj/screen-res.php?scrwidth=” + scrwidth + “& scrheight=” + scrheight;
} else
exit();</script>
</header>
<body>
Processing….
</body>
</HTML>
Save the above code as in HTML file(screen.html) then open the page in your browser. When this code has executed, it will redirect the page to a PHP page(screen-res.php) where screen resolutions are displayed. The ‘screen-res.php’ page will have the below code:
<!— screen-res.php –>
<?php
print “<h1>My Screen Resolution!</h1>”;
print “Screen Width : “.$_GET['scrwidth'].”<br/>”;
print “Screen Height : “.$_GET['scrheight'].”<br/>”;
?>
I hope I made myself clear with passing variables from JavaScript to PHP using POST method. Passing JavaScript variables in PHP is very much similar to sending any HTML form’s data using GET method.
