This article was co-authored by wikiHow staff writer, Darlene Antonelli, MA. Darlene Antonelli is a Technology Writer and Editor for wikiHow. Darlene has experience teaching college courses, writing technology-related articles, and working hands-on in the technology field. She earned an MA in Writing from Rowan University in 2012 and wrote her thesis on online communities and the personalities curated in such communities.
This article has been viewed 20,335 times.
Learn more...
In many instances, JavaScript is used on the client-side and PHP is used on the server-side of a website. This wikiHow will teach you how to pass variables (or data) between JavaScript and PHP using either a "GET/POST" method or using cookies.
Steps
Using "GET/POST" Commands
-
1Enter the following code into your HTML:
<!DOCTYPE html> <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>
- This code lets the user to your website enter information.[1]
-
2Enter the following code into your PHP code on your server:
<?php $result = $_GET['data']; echo $result; ?>
- Even though the user entered information in a JavaScript environment, their data will be passed through to PHP on the server-side.
Advertisement -
3Test your code. Upload the new code to your website, generally using an FTP. After it's uploaded, enter test data to see if your code works.
Using Cookies
-
1Enter the following code into your website coding:
<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>
-
2Enter the following code for your server to use:
<?php echo $_COOKIE["gfg"]; ?>
- As coded, the cookies will expire within 10 days.
-
3Test your code. Upload the new code to your website and visit it to see if the cookies are working.
About This Article
1. Enter the following code into your HTML.
2. Enter the following code into your PHP code on your server.
3. Test your code.