Prevent Blank Username/Password with JavaScript and Submit via PHP

Last updated 2 weeks, 4 days ago | 27 views 75     5

Tags:- JQuery PHP

First page link: Prevent Form Submission if Username and Password Are Empty Using JavaScript

Sure! Let’s extend the form validation example to include PHP code for form submission. We’ll still use JavaScript to prevent submission if fields are blank, and if the form is valid, it will submit to a PHP script that processes the input.


✅ Prevent Blank Username/Password with JavaScript and Submit via PHP


Final Structure Overview

  1. HTML + JavaScript — Validates fields before submission

  2. PHP (process.php) — Processes the form data

  3. Safe Practices — Input sanitization and feedback


HTML + JavaScript: Form Validation

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Login Form</title>
</head>
<body>
  <h2>Login</h2>
  <form id="loginForm" method="post" action="process.php">
    <label>Username:</label>
    <input type="text" id="username" name="username" /><br /><br />

    <label>Password:</label>
    <input type="password" id="password" name="password" /><br /><br />

    <p id="errorMsg" style="color:red;"></p>

    <button type="submit">Login</button>
  </form>

  <script>
    document.addEventListener("DOMContentLoaded", function () {
      const form = document.getElementById("loginForm");
      const username = document.getElementById("username");
      const password = document.getElementById("password");
      const errorMsg = document.getElementById("errorMsg");

      form.addEventListener("submit", function (event) {
        if (username.value.trim() === "" || password.value.trim() === "") {
          event.preventDefault();
          errorMsg.textContent = "Both username and password are required.";
        }
      });
    });
  </script>
</body>
</html>

PHP Script: process.php

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize input
    $username = trim($_POST["username"] ?? '');
    $password = trim($_POST["password"] ?? '');

    if (empty($username) || empty($password)) {
        echo "<p style='color:red;'>Username and password are required.</p>";
        echo "<p><a href='javascript:history.back()'>Go back</a></p>";
        exit;
    }

    // Example authentication logic (replace with DB query in real usage)
    if ($username === "admin" && $password === "secret123") {
        echo "<p style='color:green;'>Login successful! Welcome, $username.</p>";
    } else {
        echo "<p style='color:red;'>Invalid username or password.</p>";
        echo "<p><a href='javascript:history.back()'>Try again</a></p>";
    }
} else {
    echo "<p style='color:red;'>Invalid request.</p>";
}
?>

✅ Summary

Step-by-Step Flow:

  1. User fills form

  2. JavaScript checks for blank fields

  3. If filled, form submits to process.php

  4. PHP sanitizes and processes input

  5. Feedback is displayed


Tips

  • Use PHP's htmlspecialchars() if echoing user data

  • Always sanitize and validate input server-side (never trust the client alone)

  • Use HTTPS to protect form data


⚠️ Common Pitfalls

Pitfall Fix
JS doesn't prevent form Ensure you're using event.preventDefault() correctly
PHP file accessed directly without POST Add $_SERVER["REQUEST_METHOD"] check
Form submits with spaces only Use trim() on both JS and PHP sides
Echoing user input directly Wrap with htmlspecialchars() to prevent XSS