How to pass JavaScript variables to PHP ?
Last Updated :
09 Jan, 2025
JavaScript is the client side and PHP is the server-side script language. The way to pass a JavaScript variable to PHP is through a request.
Below are the methods to pass JavaScript variables to PHP:
Using GET/POST method
This example uses the form element and GET/POST method to pass JavaScript variables to PHP. The form of contents can be accessed through the GET and POST actions in PHP. When the form is submitted, the client sends the form data in the form of a URL such as:
https://example.com?name=value
This type of URL is only visible if we use the GET action, the POST action hides the information in the URL.
Client Side:
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>

Server Side(PHP):
On the server side PHP page, we request for the data submitted by the form and display the result.
php
<?php
$result = $_GET['data'];
echo $result;
?>
Output:

Client Side: Use Cookie to store the information, which is then requested in the PHP page. A cookie named gfg is created in the code below and the value GeeksforGeeks is stored. While creating a cookie, an expire time should also be specified, which is 10 days for this case.
JavaScript
// 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) {
let expires;
if (days) {
let 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=/";
}
Server Side(PHP): On the server side, we request for the cookie by specifying the name gfg and extract the data to display it on the screen.
php
<?php
echo $_COOKIE["gfg"];
?>
Output:

Using AJAX
Client Side: JavaScript code sends the variable to a PHP script using AJAX. In this example, we’ll use the XMLHttpRequest object to send a POST request to a PHP script.
JavaScript
var dataToSend = "variableName=" + encodeURIComponent(variableValue);
// Prepare the data to send
var xhr = new XMLHttpRequest();
// Create a new XMLHttpRequest object
xhr.open("POST", "your_php_script.php", true);
// Specify the request method, PHP script URL, and asynchronous
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Set the content type
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
// Check if the request is complete
if (xhr.status === 200) {
// Check if the request was successful
console.log(xhr.responseText);
// Output the response from the PHP script
} else {
console.error("Error:", xhr.status);
// Log an error if the request was unsuccessful
}
}
}
;
xhr.send(dataToSend);
// Send the data to the PHP script
Server Side (PHP): The PHP script receives the variable sent via AJAX and processes it accordingly.
PHP
// PHP code (your_php_script.php)
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["variableName"])) {
$receivedVariable = $_POST["variableName"];
// Process the received variable here
echo "Received variable: " . $receivedVariable;
} else {
echo "No data received";
}
Output:

pass JavaScript variables to PHP ?
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Similar Reads
How to pass variables and data from PHP to JavaScript ?
In this article, let's see how to pass data and variables from PHP to JavaScript. We can pass data from PHP to JavaScript in two ways depending on the situation. First, we can pass the data using the simple assignment operator if we want to operate on the same page. Else we can pass data from PHP to
3 min read
How to pass PHP Variables by reference ?
By default, PHP variables are passed by value as the function arguments in PHP. When variables in PHP is passed by value, the scope of the variable defined at function level bound within the scope of function. Changing either of the variables doesn't have any effect on either of the variables. Examp
2 min read
How to pass a PHP array to a JavaScript function?
Passing PHP Arrays to JavaScript is very easy by using JavaScript Object Notation(JSON). Method 1: Using json_encode() function: The json_encode() function is used to return the JSON representation of a value or array. The function can take both single dimensional and multidimensional arrays. Steps:
3 min read
How to run JavaScript from PHP?
JavaScript is the client side scripting language and PHP is the server side scripting language. JavaScript is used as client side to check and verify client details and PHP is server side used to interact with database. In PHP, HTML is used as a string in the code. In order to render it to the brows
2 min read
How to pass form variables from one page to other page in PHP ?
Form is an HTML element used to collect information from the user in a sequential and organized manner. This information can be sent to the back-end services if required by them, or it can also be stored in a database using DBMS like MySQL. Splitting a form into multiple steps or pages allow better
4 min read
How to convert PHP array to JavaScript or JSON ?
PHP provides a json_encode() function that converts PHP arrays into JavaScript. Technically, it is in JSON format. JSON stands for JavaScript Object Notation. Statement: If you have a PHP array and you need to convert it into the JavaScript array so there is a function provided by PHP that will easi
2 min read
How to Declare a Global Variable in PHP?
Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. Syntax:$variable_name = data; The below programs illustrate how to declare global variables. Example 1: [GFGTABS] php
2 min read
How to Assign Multiple Variables in One Line in PHP ?
In PHP, assigning multiple variables in one line can be a handy and efficient way to streamline your code. This technique not only makes your code more concise but also improves readability. There are several approaches to achieve this, each with its own syntax and use cases. Table of Content Using
2 min read
How to get parameters from a URL string in PHP?
The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: The page URL and the parameters are separated by the ? character. parse_url() FunctionThe parse_url() function is used to return the components of a URL by parsing it. It parses a URL and retu
2 min read
How to make a redirect in PHP?
Redirection from one page to another in PHP is commonly achieved using the following two ways:Using Header Function in PHP: The header() function is an inbuilt function in PHP which is used to send the raw HTTP (Hyper Text Transfer Protocol) header to the client. Syntax: header( $header, $replace, $
2 min read