PHP + Ajax Login

PHP + Ajax Login

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Debugging PHP + Ajax Login Flows: Why Your Form Reloads Instead of Submitting

When a developer switches from a traditional form submission to an AJAX request, the browser's default behavior changes significantly. In your specific case, the page reloads regardless of the credentials because the form's default action is still firing. HTML forms have a built-in mechanism that, upon hitting the submit button, automatically dispatches the data to the URL specified in the action attribute (or the current URL if omitted) using the method defined by the method attribute.

Your HTML snippet defines <form id="loginform" method="post">. Unless you explicitly set an action attribute that points to a non-existent handler, or unless your JavaScript intercepts this event before the default action occurs, the browser will attempt a standard POST request immediately after the user clicks "Login". This standard POST causes a full page reload, which overwrites any asynchronous response your AJAX script might have sent back.

To resolve this, you must prevent the default form submission behavior in your jQuery handler. You can do this by calling event.preventDefault() at the start of your submit event listener. This tells the browser to pause and wait for your JavaScript code to execute before attempting the network request.

Here is how that specific block needs to look:

$('#loginform').submit(function(event) {
    // Stop the form from submitting via a full page reload
    event.preventDefault(); 

    $.ajax({
        type: "POST",
        url: '/class/login.php',
        data: {
            username: $("#username").val(),
            password: $("#password").val()
        },
        success: function(data) {
            if (data === 'Login') {
                window.location.replace('/user-page.php');
            } else {
                alert('Invalid Credentials');
            }
        }
    });
});

Once the default action is suppressed, your AJAX request will fire in isolation. If you inspect the Network tab in Firebug (or DevTools), you will see a POST request going to /class/login.php without a subsequent HTTP redirect or page reload occurring immediately after.

However, there is a secondary issue in your provided PHP code that needs attention regarding security and architecture. You are hashing the password client-side in JavaScript (md5($this->password) is actually inside the PHP bindValue, but looking closely at your logic, you are sending plain text from JS). Wait, looking closer at the PHP snippet: $stmt->bindValue("password", md5($this->password), PDO::PARAM_STR);. This is a critical misunderstanding. You are hashing the password inside the PHP script after retrieving it. While this prevents direct SQL injection on that column, relying solely on MD5 for authentication is outdated and insecure; modern standards recommend bcrypt or Argon2. More importantly, you should never expose raw passwords in session data or logs.

Furthermore, your PHP class instantiation logic appears flawed in the context of a simple script file. The line $con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD); uses magic constants (DB_DSN, etc.). While this works if those are defined globally in config.php, it is brittle for AJAX endpoints which might be loaded differently depending on your autoloader setup. A better approach is to rely on an autoloader or ensure the class is instantiated correctly without relying on global variable pollution that often trips up dynamic loaders.

If you prefer a more structured approach that avoids manual controller pages, consider using a framework like Laravel. Frameworks handle event interception, session management, and CSRF protection out of the box. For instance, creating a simple form in Laravel requires minimal AJAX code because the framework manages the preventDefault logic via its request lifecycle or specific directives. You can find examples of handling form submissions in modern PHP environments at https://laravelcompany.com. This eliminates the need to manually write the event.preventDefault() line every time, reducing the chance of human error when switching between synchronous and asynchronous submission methods.

In summary, the immediate fix is adding event.preventDefault() to your jQuery callback. Long-term, review your authentication strategy to use stronger hashing algorithms and consider adopting a framework to manage the complexity of stateful sessions and database interactions safely.

Our network