How to include a Javascript variable inside a php function?
-
Hi! I'd like to know if there's a way I can call a javascript variable in a php function? Like for example, the code below would get the value of textbox text1 when the button is clicked. It should call the javascript function with a parameter. That javascript function calls the PHP function with a javascript variable nVal. Fuction PassNumber(nVal) { alert("<?php ShowNumber("+nVal+"); ?>"); }
Thanks. -
Hi! I'd like to know if there's a way I can call a javascript variable in a php function? Like for example, the code below would get the value of textbox text1 when the button is clicked. It should call the javascript function with a parameter. That javascript function calls the PHP function with a javascript variable nVal. Fuction PassNumber(nVal) { alert("<?php ShowNumber("+nVal+"); ?>"); }
Thanks.No. If you really want to get a value into Javascript from PHP without reloading the page, the way to do it is using AJAX.
-
Hi! I'd like to know if there's a way I can call a javascript variable in a php function? Like for example, the code below would get the value of textbox text1 when the button is clicked. It should call the javascript function with a parameter. That javascript function calls the PHP function with a javascript variable nVal. Fuction PassNumber(nVal) { alert("<?php ShowNumber("+nVal+"); ?>"); }
Thanks.You have to think about it this way: PHP code works with what the server "knows". Javascript code works with what the browser / client "knows". To get them to interact, you need to explicitly "pass" information back and forth between the two. For example, if you have a variable in the javascript, you can "pass" the value to the server by passing it with a GET variable, e.g.
<script language="javascript">
Fuction PassNumber(nVal) {
location.href = 'mypage.php?n='+nVal;
}
</script>Then, on the server side, you receive the GET variable to produce the effect that you want:
<?php
$nval = $_GET['n'];
if ($nval)
{
print('<script>alert('.$nval.');</script>');
}
?>Contrariwise, when you have the PHP variable on the server side, you can use that to feed it to the Javascript function when rendering your onclick function:
<input type="text" name="text1" value="200" /><br />
<input type="button" value="Go" onClick="PassNumber(this.text1.value+<?php print($nval) ?>)" />This requires a re-load of the page, and change of URL, each time you click the button. To do it more "subtley", without a reload, you would have to use AJAX: but the principle would be the same. Pass the information between Server and Browser using calls to the PHP page with GET.
--Greg