JavaScript and PHP
How JavaScript variable are retrieved from PHP script? How PHP variable are used in JavaScript? We will stydy all the cases.
Using form's value in PHP
Using the content of forms in PHP. Name of elements of a form are also PHP variables as soon as the PHP script is the action of the form.
Example, the complete form:
<form method="post" name="myform" action="php-form-code.php">
<input type="text" name="mytext" maxlength="80" size="30">
<input type="submit" value="Submit" >
</form>
The PHP script:
<?php echo $mytext; ?>
The $mytext variable is the name given to the text input object in the
form above.
Actually, when a file is loaded by the action property of a form, all objects
of the form are given as parameters to the script file, with the format:
?name=value&name2=value2 ...
And these parameters become variables and values in a PHP script.
In this
case:
?mytext="the entered text"
here the value is the text you have typed.
See the demo.
Variables from JavaScript are available in PHP if the flag register_globals is on. Otherwise you have to use an array instead:
$mytext = $_POST["mytext"];
Sending extra variables as parameters
And if you want to execute a script with the values of the objects of a
form, and you want also send some values that are not obtained through the
form, how to process?
A simple solution is the use of hidden objects, as this one:
<input type="hidden" name="extra" value="Content of the extra variable" >
This is a special kind of object that is not visible in the form, and that has no pupose but to hold a value that will be added to other values provided by the form.
See a demo.
If you want to change dynamically the value to pass to the script, you can assign the object above, example:
document.myform.extra.value = "some value";
Using PHP variable in an HTML page
Once the PHP code is included, with the following statements:
<?php
require("some-script.php";
?>
anything may be inserted in the page with the echo command:
<?php echo "this text is displayed in the page"; ?>
You can assign directly a value to a property of an object in this manner.
This is a common error to include PHP code in JavaScript and expecting
the PHP code to use JavaScript results. Actually PHP is processed by the
server before the page is loaded and the JavaScript code is processed after
the page has been loaded. There is no mean to the PHP code to use the results
of the JavaScript code, one should use Ajax instead.
Permission is granted to print this page and the code of the scripts and to use freely the code.
Don't display this page and the code on another website.