I want to set a variable based on the selection from a dropdown menu. I don't want the page to reload and preferably I want it run on the server side. how can I transfer a html form value to the server and put it into a PHP variable ? Here is the form; <form name="form" method="POST" action=""> <select name="number" onchange="this.form.submit();" method="post"> <option value="">Select Number</option> <option value="1">Population A</option> <option value="2">Population B</option> <option value="3">Population C</option> </select> </form> Code (markup):
[html file] <html> <head> <script type="text/javascript"> function toVar(val) { [FONT=Monaco][COLOR=#931a68]if[/COLOR](window.XMLHttpRequest)xmlhttp=[COLOR=#931a68]new[/COLOR] XMLHttpRequest();[COLOR=#931a68]else[/COLOR] xmlhttp=[COLOR=#931a68]new[/COLOR] ActiveXObject([COLOR=#3933ff]"Microsoft.XMLHTTP"[/COLOR]); [/FONT] [FONT=Monaco]xmlhttp.onreadystatechange=[COLOR=#931a68]function[/COLOR](){[/FONT] [FONT=Monaco][COLOR=#931a68]if[/COLOR](xmlhttp.readyState==4 && xmlhttp.status==200){[/FONT] [FONT=Monaco]alert('Done');[/FONT] [FONT=Monaco]}[/FONT] [FONT=Monaco][COLOR=#931a68]else[/COLOR][/FONT] [FONT=Monaco];[/FONT] [FONT=Monaco]}[/FONT] [COLOR=#3933FF][FONT=Monaco][COLOR=#000000]xmlhttp.open([/COLOR]"GET"[COLOR=#000000],[/COLOR]"index.php?value="+val[COLOR=#000000],[/COLOR][COLOR=#931a68]false[/COLOR][COLOR=#000000]);[/COLOR][/FONT][/COLOR] [FONT=Monaco]xmlhttp.send(); } </script> <head> <body> [COLOR=#101010][FONT=Courier]<form name="form" method="POST" onsubmit="return false;">[/FONT][/COLOR] [COLOR=#101010][FONT=Courier]<select name="number" method="post">[/FONT][/COLOR] [COLOR=#101010][FONT=Courier]<option value="">Select Number</option>[/FONT][/COLOR] [COLOR=#101010][FONT=Courier]<option value="1" onclick="toVar(1)">Population A</option>[/FONT][/COLOR] [COLOR=#101010][FONT=Courier]<option value="2" onclick="toVar(2)">Population B</option>[/FONT][/COLOR] [COLOR=#101010][FONT=Courier]<option value="3" onclick="toVar(3)">Population C</option>[/FONT][/COLOR] [COLOR=#101010][FONT=Courier]</select>[/FONT][/COLOR] [COLOR=#101010][FONT=Courier]</form>[/FONT][/COLOR] </body> </html> Code (markup): [index.php file] <?php if(isset($_GET['value'])) $my_var = htmlspecialchars($_GET['value']); Code (markup): not tested. I hope it works.[/FONT]
You also might want to looking into jQuery's $.post variable - it initializes an AJAX for you without having to write the AJAX initialization yourself