Using PHP to reload a page with new div content



I have a page that has main content and a menu bar, when a user logs in a $_SESSION variable is set via data pulled from a database to determine which main content and which menu bar the user sees.

The main page is along the lines of:

 <div id="menu">
    <?php include_once '/files/'.$_SESSION['menu']; ?>
    </div>

    <div>
    <?php include_once '/files/'.$_SESSION['content']; ?>
    </div>

When the user logs in the $_SESSION variables are set to “menu1.php” and “content1.php” or “menu2.php” and “content2.php”, this works fine and the page loads correctly.

I have then included two buttons on the both menu bars as such:

  <form action='' method='POST'>
      <button type="submit" name="set1">Set 1</button>
    </form>
    <form action='' method='POST'>
      <button type="submit" name="set2">Set 2</i></button>
    </form>

And two “functions”:

 <?php
      if(isset($_POST['set2'])){
            unset($_SESSION['menu']);
            unset($_SESSION['content']);
            $_SESSION['menu'] = 'menu2.php';
            $_SESSION['content'] = 'content2.php';
      };
      if(isset($_POST['set1'])){
            unset($_SESSION['menu']);
            unset($_SESSION['content']);
            $_SESSION['menu'] = 'menu1.php';
            $_SESSION['content'] = 'conent1.php';
      };
     ?>

If you were to click the button to change the content and menu from 1 to 2, the page reloads with the correct content being shown “content2”, however, the menu bar remains at “menu1”, if you were to refresh the page only then does the menu change to “menu2”, it’s as if the menu session is one refresh behind. This occurs vice versa from 2 to 1.

What can be done so that when the page reloads, it reloads with both the new content and the new menu?

Answer

I found the problem was that $_SESSION variables sometimes require a page change, not just a refresh.

So in the action of the form where the button is I created a new php page containing the two php functions and then a header() to relocate me back to the home page:

<form action='changeContent.php' method='POST'>
  <button type="submit" name="set1">Set 1</button>
</form>
<form action='changeContent.php' method='POST'>
  <button type="submit" name="set2">Set 2</i></button>
</form>

the action now directs me to changeContent.php and on that page I have the fucntions:

 <?php
  if(isset($_POST['set2'])){
        $_SESSION['menu'] = 'menu2.php';
        $_SESSION['content'] = 'content2.php';
        header("Location: ". $_SERVER['HTTP_REFERER']);
  };
  if(isset($_POST['set1'])){
        $_SESSION['menu'] = 'menu1.php';
        $_SESSION['content'] = 'conent1.php';
        header("Location: ". $_SERVER['HTTP_REFERER']);
  };
 ?>

Now when the button is clicked you are redirected to the page and the content is fully changed as expected.



Source: stackoverflow