PHP Refresh button onclick

PHP Refresh button onclick

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

Stefan Bogdanescu

Founder & Senior Architect

Why window.location.reload() Fails to Remove Items from a PHP List

You are attempting to solve a classic state management problem: you want an immediate visual update after a user action without leaving the page. Your current approach places onclick="window.location.reload();" directly on the submit button inside your while loop. While this technically reloads the browser tab, it fails to achieve the goal of "removing the entry right away" because the underlying data logic has not yet executed before the screen repaints itself.

The core issue lies in the order of execution and where the state change actually happens. When you click a button with an onclick attribute that triggers window.location.reload(), the browser immediately interrupts the current page lifecycle. It discards the current HTML, sends a new GET request to the server URL, and renders the response from scratch. In your specific implementation, the removal logic is likely handled via a POST request (implied by the submitAdd name) or a separate AJAX call that hasn't even fired yet when the reload command executes.

Furthermore, looking at your provided code snippet, you are using a standard PHP while ($row = mysql_fetch_array(...)) loop to render a table. This is a synchronous rendering model. The browser waits for the entire PHP script to finish executing and sending the HTML string before it can interact with the page. If the "Add to Cart" action requires updating the database or modifying the session array $_SESSION['selected_items'], this update must happen on the server side before the next line of code is rendered.

By relying solely on window.location.reload(), you are essentially hitting a hard reset. The browser sees the page, processes the click event, and immediately says, "Forget everything I just showed you; fetch the page again from the start." Since the removal logic hasn't run yet (because it requires server-side processing), the reloaded page simply shows the old data where the item is still present.

To make the entry disappear instantly upon clicking, you need to decouple the user action from the full page lifecycle. The most robust solution for this scenario involves using JavaScript to intercept the click event and send an asynchronous request to update the state, rather than reloading the entire document.

You should replace the direct onclick reload with a script that targets the specific row or button. Here is how you might structure that interaction:

<input type="submit" name="submitAdd" value="Add to Cart" id="btn-<?= $row['Item_ID'] ?>">
<script>
document.getElementById('btn-<?= $row['Item_ID'] ?>').addEventListener('click', function() {
    // 1. Perform the removal logic via AJAX/Fetch immediately
    fetch('/remove-item.php?id=' + <?= $row['Item_ID'] ?>) 
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 2. Remove the specific row from the DOM without reloading the page
                this.closest('tr').style.display = 'none';
                
                // Optional: Disable the button to prevent double submission
                this.disabled = true;
                this.textContent = 'Added';
            }
        });
});
</script>

This approach handles two critical aspects that the window.location.reload() method misses. First, it performs the data modification immediately via an AJAX call. Second, it manipulates the Document Object Model (DOM) directly to hide the row. This creates a seamless experience for the user who feels like the application is responsive and real-time.

It is also worth noting that your code uses mysql_fetch_array(), which relies on the deprecated MySQLi or mysqli extension syntax. If you are still using this in production, consider migrating to PDO or the newer MySQLi extension, as the old extension has reached end-of-life and poses significant security risks. Modern frameworks like Laravel handle these interactions differently by abstracting the database layer and managing session state more securely. For example, LaravelCompany provides resources on building modern PHP applications where you would typically avoid raw while loops for rendering and instead use Blade templates combined with controller logic to handle state changes efficiently.

The trade-off here is complexity versus performance. A full page reload (window.location.reload()) is computationally cheap for the server but feels sluggish to the user, especially if the list is long. An AJAX-based update adds a slight overhead to the network request but provides instant feedback, which is generally preferred in modern web applications where responsiveness is key.

Our network