In PHP, how can different actions be triggered based on the value of a form submit button using JavaScript and form actions?

To trigger different actions based on the value of a form submit button using JavaScript and form actions, you can use JavaScript to dynamically change the form action attribute based on the value of the submit button clicked. This way, you can redirect the form submission to different PHP scripts or endpoints depending on the button clicked.

<form id="myForm" method="post">
  <input type="submit" name="action" value="Action1">
  <input type="submit" name="action" value="Action2">
</form>

<script>
document.getElementById('myForm').addEventListener('submit', function(e) {
  var action = document.activeElement.value;
  
  switch(action) {
    case 'Action1':
      this.action = 'script1.php';
      break;
    case 'Action2':
      this.action = 'script2.php';
      break;
    default:
      // Default action if needed
  }
});
</script>