Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
1  
Send using ajax, or using a form ... Depend on your case too, on what you wanna do .. – StiveKnx Mar 8 '12 at 19:29

marked as duplicate by Juhana, Your Common Sense, Incognito, tereško, Graviton Mar 9 '12 at 1:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5 Answers

up vote 5 down vote accepted

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
share|improve this answer
The receiving PHP code is the file specified by yourphpfile.php. It can either be separate or part of an if block in the original PHP file. – Mike Tangolics Mar 8 '12 at 19:39

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

share|improve this answer

Try this:

var a = "Result: "+ <?php echo json_encode($parameter); ?>;
share|improve this answer

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.

share|improve this answer
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 8 '12 at 19:39

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.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.