Method 1:This example uses a form element and GET / POST method to pass JavaScript variables to PHP. The content form is accessed through the GET and POST actions in PHP. When the form is submitted, the client submits the form data as a URL such as:
https://example.com?name=value
This type of URL is only visible if if we use the GET action and the POST action hides the information in the URL.
Client side:
<
html
>
<
head
>
<
title
>
Passing JavaScript variables to PHP
< /
title
>
< /
head
>
<
body
>
<
h1
style
=
"color: green;"
>
GeeksforGeeks
< /
h1
>
<
form
method
=
"get"
name
=
"form"
action
=
"destination.php"
>
<
input
type
=
"text"
placeholder
=
"Enter Data"
name
=
"data"
>
<
input
type
=
"submit"
value
=
"Submit"
>
< /
form
>
< /
body
>
< /
html
>
Server side (PHP):On the server side PHP page, we request the data submitted in the form and display the result.
$result
=
$_ GET
[
’ data’
];
echo
$result
;
?>
Output: Method 2: Using cookies to store information:
Client side:use a cookie to store information that is then requested in the PHP page. A A cookie named gfg is generated in the code below, and the value of GeeksforGeeks is saved. When creating a cookie, you must also specify an expiration time, which in this case is 10 days. <
script
>
// Creating a cookie after the document is ready
$(document) .ready (function() {
createCookie ("gfg", "GeeksforGeeks", "10");
});
// Function to create the cookie
function createCookie (name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime (date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires =" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape (name) +" = "+
escape (value) + expires + "; path = /";
}
< /
script
>
Server side (PHP): On the server side, we request a cookie by specifying the name gfg and fetching the data to display on the screen.
echo
$_COOKIE
[
"gfg"
];
?>
Output: