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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With