Forum Moderators: open
<?
echo "<script>\n";
echo "function getyear(){\n";
echo "year_index = myform.year.selectedIndex;\n";
$yearchck = "document.write(document.forms['myform'].year[year_index].text);\n";
\\Returns the selected value from a dropdown menu.
$yearchck = "document.write(year_index);\n";
\\Returns the selected index of the dropdown.
echo "return (false);\n";
echo "}\n";
echo "</script>\n";
?>
\\ Here is the HTML Select that calls the function
<select name="year" class="customform1" id="year" size="1" onChange="getyear(this.selectedIndex);">
<option value="1996">1996</option>
<option value="1995">1995</option>
</select>
Pass a PHP variable to Java
echo "<script>";
echo "var whatever='".$phpvar."';";
echo "</script>";
PHP runs on the SERVER and JavaSCRIPT runs in the BROWSER. The two only communicate at the point a page is requested (or reloaded). That makes it impossible for client-side JavaScript to talk directly to PHP. The best you can do with JavaScript is pass parameters as GET variables.
<script>
function getyear(thisIDX){
year_index = thisIDX;
// where are you writing these two lines to?
document.write(document.forms['myform'].year[year_index].text);
document.write(year_index);
}
</script><select name="year" class="customform1" id="year" size="1" onChange="void(getyear(this.selectedIndex));">
<option value="1996">1996</option>
<option value="1995">1995</option>
</select>Pass a PHP variable to JavaSCRIPT
<?
echo "<script>";
echo "var whatever='".$phpvar."';";
echo "</script>";
?>
You're not doing anything with PHP in the writing of the function (I used the argument you are passing to it). At the end of the day, you have a normal (if a bit confusing) script. The last bit of PHP simply assigns a value of the value of "$phpvar" to the Javascript "whatever" variable. That won't change without a page reload.
It is correct that Javascript can RECEIVE data from PHP in this way, and that PHP canNOT receive any data from Javascript or anything else without a request being sent to the server and a new page being compiled in PHP.
(BTW: There is a humongous difference between Sun Microsystem's Java programming language and Netscape's Javascript scripting language. They have similar names because of an early marketing/branding effort, but are otherwise unconnected.) :)
this code is off the top of my head, so it might not work without tweaking:
HTML
<select name=example onchange="logvar('example')">
JavaScript
<script>
function logvar(what) {
loc='/phpscript.php?var=' . escape(document.myform[what].value);
logger= new Image();
logger.src = loc;
}
PHP
the code is located in phpscript.php in this example and could change session variables, log to a database, etc.