How can PHP code be optimized to avoid displaying the login form after the user has logged in without refreshing the page?

To avoid displaying the login form after the user has logged in without refreshing the page, you can use AJAX to dynamically update the content on the page. This way, when a user successfully logs in, you can send an AJAX request to the server to check the login status and update the content accordingly without reloading the entire page.

<?php
session_start();

// Check if user is already logged in
if(isset($_SESSION['user_id'])) {
    echo "Welcome, ".$_SESSION['username']."!";
} else {
    // Display login form
    echo "<form id='loginForm' method='post'>
            <input type='text' name='username' placeholder='Username'>
            <input type='password' name='password' placeholder='Password'>
            <button type='submit'>Login</button>
          </form>";
}

?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $('#loginForm').submit(function(e) {
        e.preventDefault();
        
        $.ajax({
            type: 'POST',
            url: 'login.php',
            data: $(this).serialize(),
            success: function(response) {
                $('#loginForm').html(response);
            }
        });
    });
});
</script>