HTML - Change\Update page contents without refreshing\reloading the page

HTML - Change\Update page contents without refreshing\reloading the page

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

Stefan Bogdanescu

Founder & Senior Architect

Updating Page Content Without a Refresh: Moving Beyond onclick and URL Parameters

The pattern shown in your source material—passing parameters via JavaScript to update a PHP variable on the client side—is fundamentally flawed for achieving dynamic content updates. You cannot change server-side state or re-execute PHP logic within an already loaded page simply by clicking a link or calling a function in the browser. Once the page is rendered, the HTML parser has finished its job; subsequent clicks only trigger events that the browser interprets as DOM manipulations, not new server requests.

To update a div with fresh data from a database without reloading the page, you must initiate a new network request to fetch that data and then inject the result into the DOM. This is the core principle of AJAX (Asynchronous JavaScript and XML), though modern development often uses the Fetch API or libraries like Axios.

Why Your Current Approach Doesn't Work

Your proposed solution involves using onclick attributes to pass an ID to a PHP function named recp. Let's trace what actually happens:

  1. The browser renders the page. It executes the PHP code, sets $id to '1', and displays "One" inside the div.
  2. The user clicks the link.
  3. The onclick event fires. The JavaScript executes recp('1'). However, since this function exists only in your PHP logic (which is already executed by the time the HTML is sent), the browser cannot find it unless you move that logic into a <script> tag or an external .js file.
  4. Even if you moved the logic to JavaScript, calling recp('1') updates a local variable in your script. It does not trigger a new query to the database. The HTML inside the <div id='myStyle'> remains static text until you explicitly tell it to change.

Furthermore, relying on URL parameters (e.g., changing the link to page.php?id=2) followed by a reload is the traditional way to handle state changes, but it forces the user to wait for the server response and re-render the entire page. This breaks the "single-page application" feel where interactions should be instant.

The Correct Approach: Fetching Data via AJAX

To achieve the goal of updating the content dynamically, you need a three-step cycle:

  1. Trigger: A user clicks a link or button.
  2. Request: JavaScript sends an asynchronous request (AJAX) to a new endpoint (e.g., get-data.php?id=2).
  3. Update: The server returns the new HTML content, and JavaScript injects it into the specific <div>.

Here is how you implement this using jQuery, given your existing knowledge base.

1. Create an Endpoint for Data Fetching
You cannot reuse myConnect.php directly in a link because that file executes PHP logic immediately upon being included. You need a separate script that only handles the request and outputs JSON or HTML.

Create get-data.php:

<?php
require 'myConnect.php'; // Reuse your database connection

// Ensure we are handling an AJAX request
if (isset($_GET['id'])) {
    $id = $_GET['id'];
    
    // Securely fetch data using prepared statements to prevent SQL injection
    $stmt = $pdo->prepare("SELECT para FROM content WHERE para_ID = ?");
    $stmt->execute([$id]);
    
    if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo $row['para'];
    } else {
        echo "No data found";
    }
} else {
    http_response_code(400);
    echo "Invalid request";
}
?>

2. Update the HTML and JavaScript
Replace your static links with ones that trigger a fetch when clicked. You will need to ensure your main PHP file outputs the necessary jQuery library if it isn't already there.

<!-- Updated Links -->
<a href="#" id="link-one" class="nav-item">One</a>
<a href="#" id="link-two" class="nav-item">Two</a>

<div id='myStyle'>Loading...</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    // Map IDs to the target parameter values
    const contentMap = {
        'link-one': 1,
        'link-two': 2
    };

    $('.nav-item').click(function(e) {
        e.preventDefault(); // Prevent default link navigation
        
        var $this = $(this);
        var id = contentMap[$this.attr('id')];
        
        // Fetch new data from the endpoint
        $.get('/path-to-get-data.php?id=' + id, function(response) {
            $('#myStyle').html(response); // Inject new HTML into the div
            
            // At this point, your PHP variables are effectively "new" 
            // because they were fetched fresh for this specific request.
        });
    });
</script>

Key Considerations and Trade-offs

Security: In your original code snippet, you used mysql_query with direct string interpolation (WHERE para_ID='$id'). This is vulnerable to SQL injection. Always use prepared statements (as shown in the get-data.php example) regardless of whether you are updating content dynamically or not.

State Management: You mentioned wanting PHP variables to be "new." It is important to understand that PHP is a server-side language. When the initial page loads, $id is set to '1'. When the user clicks the link, the browser does not reload the original page with new PHP code. Instead, it makes a hidden request to get-data.php. In that new script execution, you define $id based on the incoming request parameter. This effectively resets your local scope for that specific file execution without touching the user's current session state (unless you explicitly store data in $_SESSION).

Alternative: The Fetch API
While jQuery is familiar to you, the modern standard is the native fetch() API. It works similarly but requires no external library dependencies. If you decide to modernize your stack later, the syntax changes from $.get() to fetch('/path-to-get-data.php?id=' + id).then(res => res.text()), but the architectural pattern of requesting data asynchronously and updating the DOM remains identical.

For more robust server-side rendering patterns and scalable AJAX handling, exploring frameworks like Laravel can streamline these interactions. The LaravelCompany resource offers insights into building modern web applications where separating concerns between the view (HTML) and logic (PHP) is handled elegantly, often reducing the need for manual DOM manipulation entirely.

Our network