Pass Vars To/From Javascript

Description: Examples of how to pass vars from PHP to and from Javascript.

//Set the PHP variable...
$phpvariable = "Hello World!";
//..and print it into a Javascript variable.
PRINT "<script name='javascript'>";
PRINT "var jscriptvariable = '" .$phpvariable. "';";
//You can then use it for any JavaScript code you have (in this case, just a simple rollover alert)
<font color="#000000" onMouseOver="javascript:alert(jscriptvariable)">Hello World!</font><br />
<script name="JavaScript">
//This is a little trickier, but can be done using cookies
//There is of course the little problem that cookies may be disabled, but then again if you were worried about things being disabled, JavaScript may not be the right choice of scripting language for you...
//A pretty standard function for setting cookies...
function setCookie(name, value) {
   var argv = setCookie.arguments;
    var argc = setCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
     var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;
    document.cookie = name + "=" + escape(value) +
//Note: because the cookie's expiration date is null, it will not be saved to disk (so you don't have to worry about the user gaining access to the information you store on it)
        ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
        ((path == null) ? "" : ("; path=" + path)) +
        ((domain == null) ? "" : ("; domain=" + domain)) +
        ((secure == true) ? "; secure" : "");
//Put whatever JavaScript Code you need here (in this case I am just setting the variable)
var jscriptvariable2 = "<br />How are you?";
//When you are done, save the javascript variable to a cookie...
setCookie('cookiename', jscriptvariable2);
//Retrive the cookie information in PHP...
$phpvariable2 = $_COOKIE['cookiename'];
//You now have saved what was originally the Javascript variable 'jscriptvariable2' as as PHP variable $phpvariable2, and can use the PHP variable for whatever PHP purpose you want (in this case, I'm just printing it out using PHP)
PRINT $phpvariable2;

Enjoyed this post? Share it!


Leave a comment

Your email address will not be published.