简体   繁体   中英

Does include or require refresh a page? Help on changing .active in nav-bar echoed by PHP

I have a question on include , on whether require_once something.php triggers a refresh or not? It seems every new require call does trigger a refresh.

Actually, my actual question is something different but it directed my attention to the above. Please bear with a beginner like me.

On Bootstrap 5 navbar , a nav-items has a .active to make it stand out. I want to move the .active to the relevant nav-item clicked and tried this on codepen . The script works fine, but it doesn't work when using it on my toy website, where the navbar html codes are echoed out by php depending on $isLoggedIn == true || false $isLoggedIn == true || false .

The index page is composed of a header.php (which the nav-bar resides) and a requestedPage.php (which includes whatever page being requested).

When a page on the header is clicked, that generates index.php?reqPage=SomePage and included in index.php by require_once __DIR__."/pages/$reqPage.php"; , which reloads the page (including header.php), so those nav-bar items start afresh with .active in Home rather than the item clicked. Whenever I click on a nav-item, the alert Link clicked! is first shown followed by document loaded! , suggesting .active is changed and then nav-bar reloaded.

Please comment and/or advise on how to make the .active work. I am new to php and backend.

files

index.php
header.php
js/header.js
pages/page1.php
pages/page2.php
pages/page3.php...

header.php

<html>
<head>
    <!--bootstrap and jquery CDNs are here-->
    <script src="js/header.js"></script> //for changing .active in nav-item
</head> 
<body>
<?php //use php to echo out the nav-bar
if ($isLoggedIn) { //show bootstrap nav-bar for a logged-in user 
    echo "
        <nav class='navbar navbar-expand-lg navbar-dark bg-primary'>
        <div class='container'>
        <a class='navbar-brand' href='#'>Trump</a>
        <button class='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#loggedInMenus'>
        <span class='navbar-toggler-icon'></span>
        </button>
        <div class='collapse navbar-collapse' id='loggedInMenus'>
        <ul class='navbar-nav'>
            <li class='nav-item'>
            <a class='nav-link active' href='index.php?reqPage=page1'>Home</a>
            </li>
            <li class='nav-item'>
            <a class='nav-link' href='index.php?reqPage=page2'>Lions</a>
            </li>
            <li class='nav-item'>
            <a class='nav-link' href='index.php?reqPage=page3'>Tigers</a>
            </li>
        </ul></div></div></nav>
    ";
} else { //show nav-bar for an unlogged-in visitor
    echo "
        <nav class='navbar navbar-expand-lg navbar-dark bg-primary'>
        <div class='container'>
        <a class='navbar-brand' href='#'>Trump</a>
        <button class='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#unloggedInMenus'>
        <span class='navbar-toggler-icon'></span>
        </button>
        <div class='collapse navbar-collapse' id='unloggedInMenus'>
        <ul class='navbar-nav'>
            <li class='nav-item'>
            <a class='nav-link active' href='page1.php'>Home</a>
            </li>
            <li class='nav-item'>
            <a class='nav-link' href='index.php?reqPage=page4'>Dogs</a>
            </li>
            <li class='nav-item'>
            <a class='nav-link' href='index.php?reqPage=page5'>Cats</a>
            </li>
        </ul></div></div></nav>
    ";
}
?>

index.php

<?php
require_once __DIR__."/init.php"; //this contains $isLoggedIn
require_once __DIR__."/header.php"; //load the menus
$reqPage = isset($_REQUEST["reqPage"]) ? $_REQUEST["reqPage"] : null; 
require_once __DIR__."/pages/$reqPage.php"; //load the requested page

header.js

$(document).ready(function(){
  alert("document loaded!");
  $(".nav-link").on("click", function() {
    alert("Link clicked!");
    $(".navbar-nav").find(".active").removeClass("active");
    $(this).addClass("active");
    }  
  );
});

This approach uses purely PHP to achieve the goal of setting the "active" class on the correct link. I don't know if your website is database driven or not, but for simplicity, I'm using an array to store your pages

<body>
    <?php
    // DON'T use php to echo out the nav-bar.  Instead just close the PHP tag
    
    $pagesArray = array('page1' => 'Home',
                        'page2' => 'title2',
                        'page3' => 'title3',
                        'page4' => 'Dogs',
                        'page5' => 'Cats');
    
    if ($isLoggedIn) {
    //show bootstrap nav-bar for a logged-in user 
    
    ?>
            <nav class='navbar navbar-expand-lg navbar-dark bg-primary'>
            <div class='container'>
            <a class='navbar-brand' href='#'>Trump</a>
            <button class='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#loggedInMenus'>
            <span class='navbar-toggler-icon'></span>
            </button>
            <div class='collapse navbar-collapse' id='loggedInMenus'>
            <ul class='navbar-nav'>
    <?php
    // Open PHP tag again
    foreach($pagesArray AS $key => $value){
      //  Loop through your pages array (or sql loop, etc)
      $active = "";
      if ( stripos($reqPage, $key) !== FALSE) {
        //  if $key (page name) matches $reqPage make this link active
        //  if no match, $active remains empty, so when it is echo'ed,
        //  there is no class printed on the page for that anchor tag
        $active = "class='active'";
      }
      echo "<li class='nav-item'>
                <a class='nav-link' ".$active." href='index.php?reqPage=".$key."'>".$value."'</a>
                </li>";
      } // END while loop
        // close PHP tag again
      ?>
      </ul></div></div></nav>
    <?php
    } // END if logged in
    ?>
    </body>

Given my code organization where the navbar is inside header.php and included into index.php , and that the requested page variable $reqPage only resides in index.php , I cannot test $reqPage = $page inside header.php to identify the selected page before echoing out each nav-item.

  • $page exists in header.php before echoing out each nav-item
  • when user clicks on a link, its value goes to index.php as $_GET[""]
  • it is assigned to $reqPage in index.php
  • so $page and $reqPage exist in different places at different times, and cannot be tested before echo out, so testing for equality and then add .active to the echo doesn't work

Instead, I echo out the nav-bar in header.php and only identify the requested page and then add .active in index.php using JS.

header.php

 <nav class='navbar bg-primary'>
        <div class='container'>
        <a class='navbar-brand' href='#'>Trump</a>
        <button class='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#menus'>
        <span class='navbar-toggler-icon'></span>
        </button>
        <div class='collapse navbar-collapse' id='menus'>
        <ul class='navbar-nav'>

<?php //php to dynamically echo out each navbar menu dependent on login 

//array to contain nav-items for logged-in / unlogged-in users
$loggedInMenu = ["Home" => "home", "Lions" => "lions", "Tigers" => "tigers", "Log Out" => "logout"];
$unloggedInMenu = ["Home" => null, "Log In" => "login", "Sign Up" => "signup"]; 

//produce either Logged-in menus or Unlogged-in menus
if ($isLoggedIn) { 
    produceNavMenu($loggedInMenu);
} else { 
    produceNavMenu($unloggedInMenu);
}

//helper function to echo out the nav-menu by nav-items one by one
//@param $menu must be associative array having Title => reqPage
function produceNavMenu(array $menu) {
    foreach($menu as $title => $page) {
        echo "<li class='nav-item'> 
            <a class='nav-link' id='$page' href='index.php?reqPage=$page'>$title</a>
            </li>";
    }
}

?>
        </ul></div></div></nav><!--end of navbar-->

index.php

<?php
require_once __DIR__."/init.php"; //this contains $isLoggedIn
require_once __DIR__."/header.php"; //load the menus
$reqPage = isset($_REQUEST["reqPage"]) ? $_REQUEST["reqPage"] : null; 
require_once __DIR__."/pages/$reqPage.php"; //load the requested page
?>

<script> //js to add .active to the relevant nav-item
$(document).ready( function() {
  var reqPage = "<?php echo "$reqPage"; ?>"; //php var to js var
  var activeID = "#"+reqPage; //html id
  $(activeID).addClass("active"); //add .active to the requested page
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM