-2
var javascript_variable = $("#ctl00").text();
<?php $php_variable = ?> document.write(javascript_variable); <? ; ?>

I want to pass the above javascript_variable into php_variable. This code is giving me an error. Any ideas on how?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
X10nD
  • 21,638
  • 45
  • 111
  • 152
  • possible duplicate of [javascript to php variable](http://stackoverflow.com/questions/6084216/javascript-to-php-variable) – Gordon Jun 30 '11 at 11:17
  • possible duplicate of [How can I use a javascript variable as a php variable](http://stackoverflow.com/questions/2379224/how-can-i-use-a-javascript-variable-as-a-php-variable/2379251#2379251) – Gordon Jun 30 '11 at 11:28

1 Answers1

3

You cannot do that.

PHP is executed on your server. Javascript on the otherhand is executed on your client's machine in the browser.

There are two different execution context. While you can pass a PHP variable into Javascript, you cannot do the opposite since PHP is executed first and the JavaScript code is the output of your PHP code.

If you want to send a Javascript variable to PHP, you have to do with in a separate request either via a cookie or an AJAX request. Here's an example:

$.ajax({
  url: 'receivingScript.php',
  data: {'value': $("#ct100").text()}
});
Andrew Moore
  • 93,497
  • 30
  • 163
  • 175
  • I want to insert it to the db, and this needs to be done via php – X10nD Jun 30 '11 at 11:16
  • 1
    @Jean: Is `#ct100` an `` by any chance? Just submit the form and use `$_POST` or `$_GET`. – Andrew Moore Jun 30 '11 at 11:19
  • +1. Don't be confused, Jean, by the fact that you may write PHP and Javascript code in the same file. The PHP is executed as a pre-processing step, long before Javascript comes into the equation; indeed, the Javascript and HTML is the _output_ of your PHP script. You cannot feed data back into earlier execution phases. – Lightness Races in Orbit Jun 30 '11 at 11:21