faqts : Computers : Programming : Languages : JavaScript : Language Core

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

47 of 75 people (63%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I pass variables from JavaScript to PHP on the same page?

Aug 24th, 2003 22:15
J. Carroll, Juergen Thelen, Tom,


You can't.
JavaScript doesn't know anything about PHP, so they cannot interact 
directly. Common way to pass values from JS to PHP is HTTP POST or
HTTP GET the values via document.form.submit(), requesting a PHP file.
See $HTTP_POST_VARS, $HTTP_GET_VARS in your PHP documentation.
Hth, Juergen
Other Possibilities:
(1) COOKIES - you can set a cookie in javascript, and retrieve it with 
PHP using $_COOKIE["theName"]
(2) document.write - if your code flow allows, you can - theoretically -
 write out some php code to populate global var(s)...
(3) nastiest yet ... you can use serialized objects ... check out the 
old cold fusion method (wddxserializer - if still available).  also 
*theoretically* in JavaScript 1.5 you can use 
_serialize/_deserialize ... (see  
http://www.mozilla.org/rhino/serialization.html etc.)
(4) last and least likely -  if you can make javascript create a new 
document(XML for example), php can read and parse it ...
I typically use hidden form variables and cookies myself.  Good Luck!