0
How to assign javascript variable to php variable? Other than Cookiesđ
11 Answers
+ 8
The Javascript variables can be posted to the PHP page using HTTP POST or HTTP GET.
Then, the PHP code can extract the values using code like below:
#Querystring value
$age = $_GET["age"];
or
#Web Form Post value
$age = $_POST["age"];
or
#Either Post or Get values
$age = $_REQUEST["age"];
+ 5
Kode Krasher It sounds like you had fun getting this figured out on your computer before hitting that brick wall with running it in SL.
I already knew it wasn't going to work on SL, so I didn't bother trying to demo it the post back scenario. đ
That said, a few days ago, I originally misread this question and thought the OP was asking about how to initialize JS variables from PHP variables.
So... at first, I wrote the following code to demonstrate:
https://code.sololearn.com/wV6m8X2M1tXD/?ref=app
After realizing this question was about setting PHP variables from the client, I decided to simply explain the 3 different Super Globals objects that can be used to extract values other than using $_COOKIES.
I'm sharing this code with you now since I think you might be able to connect the dots on how it can be further extended to include the PHP code to handle the post back scenario with hidden inputs. đ
Hopefully, this code is somewhat helpful. But I think you already get it. đ
+ 3
Many had asked this question, and many had tried to answer with different approaches. But I'm still thinking it's not possible because Javascript runs on front-end, while PHP runs on back-end. How can they exchange memory when they run on different engine?
+ 3
As Kode Krasher and David Carroll suggested, you can POST the data (JS variable value) to the backend (PHP script) asynchronously.
Something like this:
JS:
const jsVar = 2021;
function setPhpVar() {
fetch(location.href, {
method: 'POST',
body: {jsVar},
});
}
PHP:
$phpVar = $_POST['jsVar'] ?? 1970;
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
+ 3
Kode Krasher Asynchronous HTTP requests have been possible with JavaScript for over 20 years. It is not really new technology.
+ 1
Kode Krasher I get it đ