Reading Time: 2 minutes

How to pass JavaScript variables to PHP

There are many ways to pass JS Variables to PHP. PHP is the scripting language used on the server, while JavaScript is used on the client. The best technique to send a JavaScript variable to PHP.

Method 1:

In this example, JavaScript variables are passed to PHP using the GET/POST method and form elements. The PHP GET and POST actions allow access to the contents’ form. The client transmits the form data in the form of a URL, such as when the form is submitted

example1.php


<?php

if (isset($_GET)) {

$result = $_GET['data'];

echo 'Submitted data ' . $result;

}

?>

m
PHP

    

<!DOCTYPE html>

<html>

<head>

<title>

Passing JavaScript variables to PHP

</title>

</head>

<body>

<form method="GET" name="form" action="">

<input type="text" placeholder="Enter Data" name="data">

<input type="submit" value="Submit">

</form>

</body>

</html>

html

Method 2: Using Cookies to store information:

Use a cookie to save the data, and a PHP page will then ask for it. The code below creates a cookie with the name age and stores the value 20 in it. An expiration date, in this case 5 days, should be included when creating cookies.

example2.php


    

<?php

if (isset($_COOKIE["age"])) {

echo 'Age: ' . $_COOKIE["age"];

}

?>

<!DOCTYPE html>

<html>

<head>

<title>

Cookies

</title>

</head>

<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script>

// Creating a cookie after the document is ready

$(document).ready(function() {

createCookie("age", "20", "5");

});

// 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>

</body>

</html>

example2.php

Categorized in:

Tagged in:

,