Quick Search:
 JavaScript: Pass vars to/from PHP Jump to:  
Category: >> JavaScript >> Pass vars to/from PHP  

<< lastnext >>

Snippet Name: Pass vars to/from PHP

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

Comment: (none)

Highlight Mode: JAVASCRIPT
Last Modified: February 27th, 2009

//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;

   Home |    Search |    Code Library |    Sponsors |    Privacy |    Terms of Use |    Contact Us © 2003 - 2024 psoug.org