How to Pass Variables from Javascript to PHP

In many instances, JavaScript is used on the client-side and PHP is used on the server-side of a website. This minHour will teach you how to pass variables (or data) between JavaScript and PHP using either a "GET/POST" method or using cookies.

Using “GET/POST” Commands

Enter the following code into your HTML:


  • This code lets the user to your website enter information.

Enter the following code into your PHP code on your server:

  • Even though the user entered information in a JavaScript environment, their data will be passed through to PHP on the server-side.

Test 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

Enter the following code into your website coding:

// 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=/”; }

Enter the following code for your server to use:

  • As coded, the cookies will expire within 10 days.

Test your code.

Upload the new code to your website and visit it to see if the cookies are working.

Leave a Comment