Practical Web Programming

Friday, February 27, 2009

How to Pass Value from Javascript to PHP

Although JavaScript and PHP is not the same technology, JavaScript being a client-side technology and PHP a server-side, you can actually pass values from PHP to JavaScript and vice-versa. To do this, all you need is to use a cookie.

In this example source code, I will create a cookie in JavaScript and retrieve the cookie value using PHP. Read on.

JavaScript code to create cookie.

<script type='text/javascript'>
function createCookie(name, value,expiredays)
{
var expiry_date = new Date();
expiry_date.setDate(expiry_date.getDate() + expiredays);
document.cookie=name+ "=" +escape(value)+
((expiredays==null) ? ""
:";expires="+expiry_date.toGMTString());
alert("'" + name + "' cookie created.");
}
</script>


HTML code to call the createCookie function.

<input type="button" value="Create Cookie using JavaScript" 
onclick="createCookie('YourName', 'Joel Badinas')"/>


HTML form for submitting request to the server for the PHP code.

<form method="POST" action=""> 
<p>
<input type="submit" name="submit" value="Get Cookie using PHP"/>
</p>
</form>


PHP code that will read the cookie.

<?php
if (isset($_POST["submit"]))
{
print "Cookie value is '".$_COOKIE["YourName"]."'";
}
?>


Putting it all together.

<html>
<head>
<title>Practical Web Programming</title>

<script type='text/javascript'>
function createCookie(name, value,expiredays)
{
var expiry_date = new Date();
expiry_date.setDate(expiry_date.getDate() + expiredays);
document.cookie=name+ "=" +escape(value)+
((expiredays==null) ? ""
:";expires="+expiry_date.toGMTString());
alert("'" + name + "' cookie created.");
}
</script>

</style>

</head>
<body>

<p method="POST" action="">
<p>
<input type="button" value="Create Cookie using JavaScript"
onclick="createCookie('YourName', 'Joel Badinas')"/>
<input type="submit" name="submit" value="Get Cookie using PHP"/>
</p>
</form>

<?php
if (isset($_POST["submit"]))
{
print "Cookie value is '".$_COOKIE["YourName"]."'";
}
?>

</body>
</html>


There you have it.

1 comments:

laura said...

Thank you for posting this blog. It's really informative, but if you want more tips and tricks on "how to pass Value from JavaScript to PHP", visit web programmer site.

Recent Post