0

Possible Duplicate:
Using a javascript variable to set PHP variable

I need to do something like this

<script type="text/javascript" charset="utf-8">
    '<?php $something; ?>' = $(".product_calculation").val();
</script>

<?php
  print "from js" . $something;
?>

so i need to set a variable and then use it in php directly below after i set it

Community
  • 1
  • 1
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321
  • Why exactly do you need to do this? PHP is run on your server, and then set to the browser where the JavaScript is ran. Maybe you can use AJAX, or a cookie to send the value to a PHP script? – gen_Eric Jun 08 '11 at 20:41

6 Answers6

8

No you cannot. PHP is executed by your server. jQuery later by clients.
What you can do is an AJAX requests with params.

dynamic
  • 46,985
  • 55
  • 154
  • 231
2

Short answer: No. Long answer: Yes.

You cannot directly affect PHP variables via jQuery since PHP runs on the server and jQuery runs on the client (after the PHP is already complete). But if you really needed to, you could make AJAX calls to the server to set variable values as long as those variables can be maintained somehow (session, database, flat file, etc) so that the next time the script runs, the value can be retrieved.

KOGI
  • 3,959
  • 2
  • 24
  • 36
0

You will need to do ajax to pass the variable back to the server. While the code is generated on the server it is executed on the Client which the server has no contact with until a request is made.See: http://api.jquery.com/jQuery.ajax/ for info on the jquery implementation.

scrappedcola
  • 10,423
  • 1
  • 32
  • 43
0

PHP executes server side and outputs HTML and Javascript. Javascript executes afterward on the client's browser. It's not possible.

What you can do instead is have Javascript set a form element or parameter and then pass that to PHP to set it. Or use AJAX as others have suggested.

Cfreak
  • 19,191
  • 6
  • 49
  • 60
0

A PHP variable exists only in the web server. Once PHP has been parsed and executed the resulting HTML is sent to your browser. That resulting page would contain your javascript which is then run in the context of the browser. So, no, what you're asking to do is not possible.

jbruni
  • 1,238
  • 8
  • 12
0

Not in that fashion. But there are various options to transfer a JS variable to PHP. (Unless you had an PHP application server a direct RPC connection for variable interchanges seems infeasible).

What you commonly can utilize however is a cookie:

document.cookie = "something="+$(".product_calculation").val();

So it will not become $something in PHP, but $_COOKIE["something"] and of course only with the very next page request.

mario
  • 144,265
  • 20
  • 237
  • 291