Pass javascript variable to php code?

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

I have a php and javascript file. I want the PHP variable to be the result of a javascript function that takes a php variable as a parameter. For instance:

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

I know that you cannot do "= echo", is there any other way to do this?

thanks

+6
source share
5 answers

You cannot do this directly, because JavaScript works on the client side, and PHP runs on the server side.

First you need to execute JavaScript, and then send the result to the server using a FORM or AJAX call.

Here's what it 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}, }); 

Getting PHP (yourphpfile.php)

 $myval = $_POST['variable']; // do something 
+12
source

PHP code runs on the server before sending a response; JavaScript starts after, in the browser. You cannot set a PHP variable from JavaScript, because there are no PHP variables in the browser where JavaScript works. You will need to use an AJAX request from JavaScript to a PHP script that stores any information you want to receive.

+3
source

Try the following:

 var a = "Result: "+ <?php echo json_encode($parameter); ?>; 
+2
source

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

+1
source

You cannot pass js variable to php code.
PHP runs on a server thousands of miles from the client where js runs.

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

0
source

Source: https://habr.com/ru/post/910271/


All Articles