[php] How can I use a JavaScript variable as a PHP variable?

I'm trying to include JavaScript variables into PHP code as PHP variables, but I'm having problems doing so. When a button is clicked, the following function is called:

<script type="text/javascript">
    function addTraining(leve, name, date)
    {
        var level_var = document.getElementById(leve);
        var training_name_var = document.getElementById(name);
        var training_date_var = document.getElementById(date);

        <?php
            $result = "INSERT INTO training(level, school_name, training_date) VALUES('level_var', 'training_name_var', 'training_date_var')" or die("Query not possible.");
        ?>

</script>

Is it possible?

This question is related to php javascript

The answer is


You can take all values like this:

$abc = "<script>document.getElementByID('yourid').value</script>";

You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data. -don


I had the same problem a few weeks ago like yours; but I invented a brilliant solution for exchanging variables between PHP and JavaScript. It worked for me well:

  1. Create a hidden form on a HTML page

  2. Create a Textbox or Textarea in that hidden form

  3. After all of your code written in the script, store the final value of your variable in that textbox

  4. Use $_REQUEST['textbox name'] line in your PHP to gain access to value of your JavaScript variable.

I hope this trick works for you.


You can do what you want, but not like that. What you need to do is make an AJAX request from JavaScript back to the server where a separate PHP script can do the database operation.


<script type="text/javascript">
var jvalue = 'this is javascript value';

<?php $abc = "<script>document.write(jvalue)</script>"?>   
</script>
<?php echo  'php_'.$abc;?>

PHP runs on the server. It outputs some text (usually). This is then parsed by the client.

During and after the parsing on the client, JavaScript runs. At this stage it is too late for the PHP script to do anything.

If you want to get anything back to PHP you need to make a new HTTP request and include the data in it (either in the query string (GET data) or message body (POST data).

You can do this by:

  • Setting location (GET only)
  • Submitting a form (with the FormElement.submit() method)
  • Using the XMLHttpRequest object (the technique commonly known as Ajax). Various libraries do some of the heavy lifting for you here, e.g. YUI or jQuery.

Which ever option you choose, the PHP is essentially the same. Read from $_GET or $_POST, run your database code, then return some data to the client.