Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass javascript variable to php code? [duplicate]

Tags:

javascript

php

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

like image 806
ewein Avatar asked Mar 08 '12 19:03

ewein


2 Answers

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
like image 158
Mike Tangolics Avatar answered Sep 24 '22 20:09

Mike Tangolics


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.

like image 45
Chuck Avatar answered Sep 25 '22 20:09

Chuck