How to assign javascript variable to php variable? Other than Cookies🙂 | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

How to assign javascript variable to php variable? Other than Cookies🙂

2nd Jan 2021, 6:06 AM
Lalindu Wenasara
Lalindu Wenasara - avatar
6 Antworten
+ 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"];
2nd Jan 2021, 8:57 AM
David Carroll
David Carroll - avatar
+ 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. 👌
7th Jan 2021, 2:42 PM
David Carroll
David Carroll - avatar
+ 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?
2nd Jan 2021, 6:18 AM
Ipang
+ 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
8th Jan 2021, 12:50 AM
Ore
Ore - avatar
+ 3
Kode Krasher Asynchronous HTTP requests have been possible with JavaScript for over 20 years. It is not really new technology.
8th Jan 2021, 1:47 AM
Ore
Ore - avatar
+ 1
Kode Krasher I get it 👌
8th Jan 2021, 2:58 AM
Ore
Ore - avatar