Re: passing values into javascript [message #179873 is a reply to message #179872] |
Sat, 15 December 2012 13:10 |
Denis McMahon
Messages: 634 Registered: September 2010
Karma:
|
Senior Member |
|
|
On Fri, 14 Dec 2012 22:09:12 -0500, richard wrote:
> As PHP creates the html page, it would be, or should be, rather simple
> to produce a line of code for that line of JS.
> Such as Echo "<script>code</script>"
Yep.
Now all you have to do is work out how to get the values you want where
you have "code".
Simples. Google "javascript variable assignment"
It's probably something like:
echo "<script type='text/javascript'>var jsvarname = {$phpvarname};</
script>\n";
If $phpvarname is a string, you'll need single or escaped double quotes
round it, either of:
echo "<script type='text/javascript'>var jsvarname = '{$phpvarname}';</
script>\n";
echo "<script type='text/javascript'>var jsvarname = \"{$phpvarname}\";</
script>\n";
If You want to pass the value of a javascript variable from one page to a
script on another page, then on the first page you need to put the
variable value into a suitable post or get request (which is a javascript
issue, not a php issue, so don't ask how to do it here), and then in the
php you need to extract the value from the request, validate it, and then
use it for $phpvariable.
How you get it into the post / get request using javascript is a
javascript topic, not a php one. You might want to google something like
"dynamically generating get request urls with javascript".
On the php side, you can check that a string in the $_POST or $_GET array
matches the expected format using a regex:
http://php.net/manual/en/function.preg-match.php
You can convert a string in the $_POST or $_GET array to an int or float
value using appropriate functions:
http://php.net/manual/en/function.intval.php
http://php.net/manual/en/function.floatval.php
So, for example, as an academic exercise, to read an integer limited to a
range of 25 .. 75 and with a default value 50 from a get request and send
it back as a javascript value, you could code something like this in the
php:
$myval1 = 50; // default value
if ( isset( $_GET['myval1'] ) && preg_match( '/^[2-7][0-9]$/', $_GET
['myval1'] ) == 1 ) {
$myval1 = intval( $_GET['myval1'] );
if ( $myval1 < 25 ) $myval1 = 25; // lower limit value
if ( $myval1 > 75 ) $myval1 = 75; // upper limit value
}
echo "<script type='text/javascript'>\nvar myval1 = {$myval1};\n</script>
\n";
Obviously you also need to make sure that the echo appears at an
appropriate point in generating the output, I normally try and put such
things in the document head before I declare any javascript functions.
Rgds
Denis McMahon
|
|
|