Click to See Complete Forum and Search --> : how do I pass a variable value in Javascript to a PHP function? HELP


jfernandez
August 25th, 2006, 12:37 AM
Hi,

I need to pass a variable value in Javascript back to PHP function as a parameter. Can I do that? Here's a snipet of my code.


<form name="form1">
<?PHP
echo "<script type=\"text/javascript\">";
echo "function go_to()";
echo "{";
echo "var location = document.form1.select1.options[document.form1.select1.selectedIndex].value;";
echo "new_location = " . $_SERVER['PHP_SELF'] . "?" . build_query($_GET, "loc", location)";
echo "alert(new_location);";
echo "}";
echo "</script>";
?>
<select name="select1" onchange="go_to()">
<option value="1" SELECTED>option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
<option value="4">option4</option>
</select>
</form>


My code is not complete, but I hope somebody can understand what I want. The user will select the dropdown called select1, then the value of the selected (1 or 2 or 3 or 4) will be assigned in Javascript to variable location. I need to pass the value of location to the 3rd parameter of the PHP function build_query(). Then print out the new string value in Javascript with alert(). What's the right way to do that?

thanks for any help.

PeejAvery
August 25th, 2006, 08:13 AM
You can't pass a JavaScript variable to the PHP directly because there has to be server interaction.

Your JavaScript function should be outside the form tags. In this case, you don't need the form tags.

[php]<?php
if(isset($_GET['location'])){$location = $_GET['location'];}
?>

<script language="JavaScript">
function send_to_php(loc){
parent.theframe.location.replace("<?php echo $_SERVER['PHP_SELF']?; >?location=" + loc);
}
</script>

<select onchange="send_to_php(this.value)">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
<option value="4">option4</option>
</select>[/html]

jfernandez
August 25th, 2006, 03:28 PM
peejavery, thanks for the reply. You're always the guys who comes forward to help.

I'll try your solution later at my home. But I doubt it's something I really want. But I'll probably come up with a better/clearer question later on of what I really want to achieve.