Go Back to Previous Page

Go Back to Previous Page

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

Stefan Bogdanescu

Founder & Senior Architect

Returning Users to Previous Pages After Form Submission

Handling form submissions often involves a specific UX pattern: collect data, process it on the server, and then redirect the user or show them where they came from. When you build a rating system where a form posts data to a separate PHP script, the immediate question is how to get that user back to their original context without losing them in a generic error page or a blank success message.

You asked if this can be done with JavaScript in your PHP script. The short answer is yes, but the implementation depends entirely on whether you want to use an automatic redirect or a client-side link. Each approach has distinct implications for SEO, browser history, and user experience.

Automatic Redirects via HTTP Headers

The most robust method for returning a user to the previous page after processing data is performing a server-side redirect using HTTP headers before rendering any HTML. This ensures the browser's address bar updates correctly and the action remains atomic from the server's perspective.

In your PHP script, after successfully processing the rating data, you can use header() to send a Location response. It is critical to call this function immediately, before any output (even whitespace) is sent to the client.

<?php
// Assume $ratingData has been validated and saved here
if ($success = saveRating($ratingData)) {
    // Extract the referrer if it exists
    $referrer = $_SERVER['HTTP_REFERER'] ?? '/default-home-page';
    
    // Perform a 302 Found redirect
    header("Location: " . $referrer);
    exit(); // Always exit after sending headers
}

// Fallback for failed submissions or missing referrer
header("Location: /");
exit();
?>

This approach is generally preferred because it handles the redirection transparently. The browser automatically navigates to the new URL, and the user never sees the success message HTML. However, relying on HTTP_REFERER can be fragile; users might navigate via bookmarks, search engines, or internal links that do not set this header. Additionally, if your PHP script is located in a subdirectory but the referrer points to the root domain, you may encounter path mismatch issues unless you normalize the URL strings carefully.

Client-Side Navigation with JavaScript

If you prefer to show a confirmation message before sending the user away—perhaps to let them know their rating was received—you can use JavaScript after the page loads. In this scenario, your PHP script processes the data and then outputs a small HTML block containing the link or a script that triggers navigation.

<div id="post-success" style="display:none;">
    <p>Thank you for your rating!</p>
    <a href="<?php echo htmlspecialchars($_SERVER['HTTP_REFERER'] ?? '/'); ?>">Return to previous page</a>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Optional: Wait a brief moment for the user to read the message
    setTimeout(function() {
        var referrer = document.referrer;
        if (referrer) {
            window.location.href = referrer;
        } else {
            // Fallback if referrer is empty or same origin
            history.back(); 
        }
    }, 2000);
});
</script>

Using window.location.href or history.back() relies on the browser's ability to track the previous URL. This method works well for interactive applications but fails in cases where the user navigated via a bookmark, a direct link, or an internal search result that doesn't populate document.referrer. Furthermore, if the referrer header is missing, falling back to history.back() can be unreliable if the browser state isn't preserved as expected.

Security and Edge Cases

Regardless of the method chosen, you must handle cases where HTTP_REFERER is empty. Users clicking bookmarks, using search engines like Google, or navigating via internal navigation menus that don't trigger a referrer header will result in an empty string. Failing to check for this leads to broken links or errors.

Additionally, if your PHP script serves as an API endpoint returning JSON instead of HTML, automatic redirects are often handled by the client-side fetch logic rather than server headers. In Laravel-based applications, you might find utility methods that handle these scenarios more gracefully, ensuring consistent behavior across different request types.

Ultimately, the choice between a hard redirect and a soft navigation depends on whether you need to present a success state or if seamless return is paramount. For high-volume rating systems, automatic redirects usually provide the cleanest user experience.

Our network