Active Stat in Navbar not working with PHP extension


I relocated this question to the PHP forum because it is not longer a JS issue (at least I think)

I have a very simple navbar which has an active state which changes on click. Now I wanted to use this navbar to order a PHP/SQL generated table.
However the way the table gets order is by using a variable which changes the php extension in the URL on click. So everytime I click the link in the navbar it resets because the extension changes (I’m guessing).

I looked online and I found a few example of how to do this when you have different php pages but I could not find anything that explained how to do it if just the php extension changes.

Here is the setup

JS function for navbar:

$(document).ready (function() {
          $("a.cp_btns").click(function() {

Divs with php links

<div id="cp_menu">
<a class="cp_btns "<?php echo'<a href="indexB.php?order_var=' . $id_var . '"';?>>Most Recent</a></a>
<a class="cp_btns" <?php echo'<a href="indexB.php?order_var=' . $fn_var . '"';?>>Best Rated</a></a>
<a class="cp_btns" <?php echo'<a href="indexB.php?order_var=' . $ln_var . '"';?>>Most Viewed</a></a>

As you can see the $id_var etc. change the php extension

One of the examples I found does something like this

$path = $_SERVER['PHP_SELF'];
$page = basename($path);
$page = basename($path, '.php');
<div id="navbar">
    <li><a<? if($page == 'one') print ' class="active"'; ?> href="one.php">Page 1</a></li>
    <li><a<? if($page == 'two') print ' class="active"'; ?> href="two.php">Page 2</a></li>
    <li><a<? if($page == 'three') print ' class="active"'; ?> href="three.php">Page 3</a></li>
    <li><a<? if($page == 'four') print ' class="active"'; ?> href="four.php">Page 4</a></li>

But as I said that only seems to be useful if the navbar links to different php pages.

Is there perhaps a way to hide the extension or would that not work?


If I read correctly, you just want to access the value of order_var correct?

$sort_by = $_GET[‘order_var’];

The ordering of the table works fine. My problem is that once I click on a link the navbar does not memorize that the link needs to stay active. It just resets to its initial state.

In other words it cannot memorize the active state after completing the task, because the php part of the page reloads, not the template surrounding it of course.

You can also store it in a session variable and check for that on each page.

if ((isset($_GET['order_var'])) && ($_GET['order_var'] != '')) {
    $_SESSION['sort'] = $_GET['order_var'];
} else {
    $_SESSION['sort'] = 'a default sort order';

// Then on whatever page needs to grab the sort order
$sort_by = $_SESSION['sort'];

I think that perhaps moving the whole php code for the order logic into the template would help because the navbar wouldnt reload?