How to pass a <td></td> value to a php variable?

Member

by orpha , in category: PHP General , 3 months ago

How to pass a <td></td> value to a php variable?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 3 months ago

@orpha 

To pass a <td></td> value to a PHP variable, you can use JavaScript to capture the value of the table cell and then send it to a PHP script using an AJAX request.


Here is an example of how you can achieve this:

  1. Add an id attribute to your element to make it easier to target with JavaScript:
1
<td id="cellValue">50</td>


  1. Add a JavaScript function that captures the value of the element and sends it to a PHP script using AJAX:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<script>
document.getElementById("cellValue").addEventListener("click", function() {
  var value = this.innerHTML;

  var xhr = new XMLHttpRequest();
  xhr.open("POST", "save_data.php", true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send("cellValue=" + value);

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      // do something with the response from the PHP script
    }
  };
});
</script>


  1. Create a PHP script (save_data.php) that receives the value from the AJAX request and assigns it to a PHP variable:
1
2
3
4
<?php
$cellValue = $_POST['cellValue'];
// do something with the value
?>


  1. Now, when the element is clicked, the value inside it will be sent to the PHP script, which can then assign it to a PHP variable for further processing.