Prevent page reload and redirect on form submit ajax/jquery

Prevent page reload and redirect on form submit ajax/jquery

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

Stefan Bogdanescu

Founder & Senior Architect

Prevent page reload and redirect on form submit ajax/jquery

The frustration of a page refreshing immediately after an AJAX request is one of the most common pain points in front-end development. It usually stems from a misunderstanding of how the browser's default form submission lifecycle interacts with event listeners. When you press "Send," the browser doesn't wait for your JavaScript to finish; it checks if the <form> element has a default action and, if so, triggers a navigation event before your $.ajax call even completes.

To fix this, you must explicitly intercept that default behavior at the moment the form attempts to submit. Relying solely on an onClick handler attached to a button inside a <form> tag is insufficient because the browser's internal submission mechanism bypasses individual child element events in favor of the parent form's submit event.

Intercepting the Default Action

The core issue in your specific scenario is that you are binding logic to the click event of an anchor tag (<a>) while simultaneously defining a <form> element with a default submission behavior. Even if you use return false or event.preventDefault() inside the onClick handler, the browser eventually processes the form's intrinsic request lifecycle unless the submit event itself is cancelled.

You need to listen for the submit event on the form container and prevent its default action there. This ensures that regardless of how the user triggers the submission (whether via a button or an anchor tag with a JavaScript call), the browser halts before sending data via HTTP POST.

Here is the corrected approach using jQuery:

$(document).ready(function() {
    $('#contact-form').on('submit', function(event) {
        // Prevent the default form submission (reload/redirect)
        event.preventDefault();

        // Gather your data manually or use serialize() if needed
        var name = $('input#name').val();
        var email = $('input#email').val();
        var comments = $('textarea#comments').val();
        
        // Construct the payload
        var formData = 'name=' + encodeURIComponent(name) + 
                       '&email=' + encodeURIComponent(email) + 
                       '&comments=' + encodeURIComponent(comments);

        $.ajax({
            type: 'POST',
            url: 'js/sendEmail.php',
            data: formData,
            success: function(results) {
                $('ul#response').html(results);
            },
            error: function() {
                // Handle errors gracefully to avoid confusing the user
                $('ul#response').html('<li>An error occurred while sending.</li>');
            }
        });
    });
});

By attaching the handler directly to #contact-form and calling event.preventDefault(), you effectively pause the browser's internal scheduler. The AJAX request now completes in the background, allowing your code to manipulate the DOM (like updating the ul#response) without the page vanishing or jumping to a new URL.

Handling the Clear Button

Your HTML includes a "Clear Form" link that calls document.getElementById('contact-form').reset(). While this works for resetting inputs, it is important to remember that .reset() does not clear hidden fields or reset values set by JavaScript variables outside the form. Furthermore, if you have event listeners attached to those specific input elements, they might still trigger logic upon reset unless cleared explicitly.

For a robust user experience, consider replacing the <a> tags with <button> elements. This aligns the semantic meaning of the element with its function. A button naturally triggers a submit event, making the event.preventDefault() pattern even more predictable. However, if your design constraints strictly require anchor tags, ensure that the AJAX logic is tied to the form's lifecycle rather than the button's click event to avoid race conditions where the browser submits the form before your script runs.

Security and Data Integrity Considerations

While preventing the redirect is crucial for user experience, it introduces a responsibility for security. When you disable the default form submission, you are bypassing the browser's built-in CSRF protection mechanisms if your backend isn't configured to validate tokens manually. Ensure that js/sendEmail.php verifies the authenticity of the request before processing data.

Additionally, always encode your data using encodeURIComponent() when constructing query strings or raw payloads. In your original code, passing plain values into data: formData can lead to malformed requests if the input contains special characters like spaces or ampersands. Encoding ensures that names with spaces (e.g., "John Doe") are transmitted correctly as name=John%20Doe.

If you are building a larger application using Laravel, this pattern of intercepting form submissions is often handled via Blade directives or middleware, but understanding the underlying jQuery mechanics remains essential for debugging and customizing behavior in vanilla JS environments. For more complex routing needs within a Laravel ecosystem, visiting https://laravelcompany.com can provide further insights into managing form handling and security best practices.

Ultimately, the solution lies not in fighting the browser with return false on every button, but in respecting the form's submit event lifecycle and cancelling the default navigation explicitly at the source.

Our network