Exchanging variables between JavaScript and PHP

How JavaScript variable are retrieved from PHP script?
And conversely, how to use the values ​​of PHP variables in JavaScript?

Form's data will be in $_POST or $_GET

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" >

"mytext" is the name given to the text input object in the form above.
The PHP script retrieves the name as key in the $_POST array:

  $mytext = $_POST['mytext'];
  echo $mytext;

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 ...

There parameters are a part of the URL with a GET request, there are invisible with POST.

And these parameters become variables and values in a PHP script.
In this case:

?mytext="the entered text"

The value is the text you have typed.

The hidden type allows to send data not provided by users

And if you want to send to the script on the server some values that are not obtained through the form, how to process?
A simple solution is the use of hidden elements, as this one:

<input type="hidden" name="extra" value="Content of the extra variable" >

This kind of element is not visible in the form, and has the only purpose add a value to other values provided by the form.

If you want to change dynamically the value to pass to the script, you can assign the value of the hidden tag, example:

document.myform.extra.value = "some value";

PHP variables are inserted in an HTML page through echo

This page must be parsed by the PHP interpreter, so have the PHP extension (unless the server is configured differently).

Once the PHP code is included, with the following statements:


...anything may be inserted in the page with the echo command:

  echo "<p>This text is displayed in the page.</p>";

This text is displayed in the page.

You can assign directly a value to a property of an object in this manner.

var x = "<?php echo $x; ?>";

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 directly results of the JavaScript code, Ajax must be used instead.


© 2007-2012 Xul.fr