How to pass a javascript variable to a PHP file?

Member

by domenico , in category: Javascript , a year ago

How to pass a javascript variable to a PHP file?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , a year ago

@domenico 

To pass a JavaScript variable to a PHP file, you can use one of the following methods:

  1. Send the variable value as a query parameter in the URL using AJAX:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var value = "example";

// Create a new XMLHttpRequest object
var xhttp = new XMLHttpRequest();

// Specify the PHP file path and add the variable as a query parameter
var url = "example.php?var=" + encodeURIComponent(value);

// Define the AJAX request
xhttp.open("GET", url, true);

// Send the request
xhttp.send();


On the PHP file (example.php), you can retrieve the JavaScript variable value using the $_GET superglobal:

1
$var = $_GET["var"];


  1. Using the Fetch API (modern alternative for AJAX):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var value = "example";

// Define the URL and add the variable as a query parameter
var url = "example.php?var=" + encodeURIComponent(value);

// Use the Fetch API to send an HTTP GET request
fetch(url)
  .then(response => response.text())
  .then(data => {
    console.log(data); // Output the response from the PHP file
  });


On the PHP file (example.php), you can retrieve the JavaScript variable value the same way as above:

1
$var = $_GET["var"];


  1. Using a form submission:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!-- HTML code -->
<form id="myForm" action="example.php" method="post">
  <input type="hidden" id="myInput" name="myInput">
  <input type="submit" value="Submit">
</form>

<script>
var value = "example";

// Set the value of the hidden input field
document.getElementById("myInput").value = value;

// Submit the form
document.getElementById("myForm").submit();
</script>


On the PHP file (example.php), you can retrieve the JavaScript variable value using the $_POST superglobal:

1
$var = $_POST["myInput"];


Note: In all these methods, make sure to validate and sanitize the variable on the server-side (PHP) to prevent any security vulnerabilities.