How can client-side scripting like JavaScript be used to enhance form interactions in PHP applications?

Client-side scripting like JavaScript can be used to enhance form interactions in PHP applications by providing instant feedback to users without requiring a page refresh. This can include validating form fields before submission, dynamically updating form elements based on user input, and displaying error messages in real-time.

<form action="submit.php" method="post" id="myForm">
  <input type="text" name="username" id="username">
  <span id="usernameError" style="color: red;"></span>
  <input type="password" name="password" id="password">
  <span id="passwordError" style="color: red;"></span>
  <button type="submit">Submit</button>
</form>

<script>
  document.getElementById('myForm').addEventListener('submit', function(e) {
    var username = document.getElementById('username').value;
    var password = document.getElementById('password').value;

    if (username === '') {
      e.preventDefault();
      document.getElementById('usernameError').innerText = 'Username is required';
    }

    if (password === '') {
      e.preventDefault();
      document.getElementById('passwordError').innerText = 'Password is required';
    }
  });
</script>