6

Possible Duplicate:
How to pass a variable / data from javascript to php and vice versa?

I have a file of php and javascript code. I want to set a php variable to be the result of a javascript function which takes a php variable as a parameter. For example:

$parameter = "this is a php variable";
$phpVar = echo "foo(" . parameter . ");";

I know you cannot do a "= echo", is there another way I can do this?

Thanks

Community
  • 1
  • 1
ewein
  • 2,695
  • 6
  • 36
  • 54

5 Answers5

12

You can't directly do that, since JavaScript runs on the client-side and PHP gets executed on the server-side.

You would need to execute the JavaScript first and then send the result to the server via a FORM or AJAX call.

Here's what that might look like:

PHP

$parameter = "this is a php variable";
echo "var myval = foo(" . parameter . ");";

JavaScript

var myval = foo("this is a php variable"); // generated by PHP

$.ajax({
  type: 'POST',
  url: 'yourphpfile.php',
  data: {'variable': myval},
});

Receiving PHP (yourphpfile.php)

$myval = $_POST['variable'];
// do something
Mike Tangolics
  • 247
  • 1
  • 4
3

PHP code is run on the server before the response is sent; JavaScript is run after, in the browser. You can't set a PHP variable from JavaScript because there are no PHP variables in the browser, where JavaScript if running. You'll have to use an AJAX request from JavaScript to a PHP script that stores whatever information it is you want to get.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • 2
    Whoever downvoted, it would be more useful to explain what you find objectionable, particularly as everyone who answered after me seems to be saying the same thing I did. Is there some important nuance I got wrong? Do you just not like people named after high-quality ground meats? – Chuck Mar 08 '12 at 19:39
3

Try this:

var a = "Result: "+ <?php echo json_encode($parameter); ?>;
devasia2112
  • 5,844
  • 6
  • 36
  • 56
1

You have to make a GET or POST request to the script from JavaScript.

hsz
  • 148,279
  • 62
  • 259
  • 315
0

You cannot pass a js variable to php code.
PHP happens to run on the server, a thousand miles away from client, where js is run.

So, you can only call a php script, using js or regular hyperlink.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345