Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to pass JavaScript variables to PHP?
You can pass JavaScript variables to PHP using several methods. Since PHP runs on the server and JavaScript runs in the browser, direct variable passing isn't possible. However, you can achieve this through AJAX requests, form submissions, or by embedding JavaScript values in PHP output.
Method 1: Using AJAX POST Request
The most common approach is to send JavaScript variables to PHP using AJAX −
<!DOCTYPE html>
<html>
<head>
<title>Pass JS to PHP</title>
</head>
<body>
<button onclick="sendData()">Send Data to PHP</button>
<div id="result"></div>
<script>
function sendData() {
var jsVariable = "Hello from JavaScript";
var xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.send("data=" + encodeURIComponent(jsVariable));
}
</script>
</body>
</html>
The corresponding PHP file (process.php) −
<?php
if ($_POST['data']) {
$receivedData = $_POST['data'];
echo "PHP received: " . htmlspecialchars($receivedData);
}
?>
Method 2: Using Form Submission
You can also pass JavaScript variables through hidden form fields −
<form id="dataForm" method="POST" action="process.php">
<input type="hidden" id="hiddenField" name="jsData" value="">
<button type="button" onclick="submitForm()">Submit</button>
</form>
<script>
function submitForm() {
var jsVariable = "Data from JavaScript";
document.getElementById("hiddenField").value = jsVariable;
document.getElementById("dataForm").submit();
}
</script>
Method 3: Embedding JavaScript in PHP Output
For displaying JavaScript variables in the same page, you can use document.write −
<script>
var res = "success";
</script>
<?php
echo "<script>document.writeln(res);</script>";
?>
Key Points
- PHP executes on the server before the page loads, JavaScript runs in the browser after
- AJAX is the most flexible method for real-time data transfer
- Always sanitize and validate data received from JavaScript
- Use
encodeURIComponent()in JavaScript andhtmlspecialchars()in PHP for security
Conclusion
While you cannot directly pass JavaScript variables to PHP, AJAX requests and form submissions provide effective solutions. Choose AJAX for dynamic interactions and forms for simple data submission.
