Responsive Dynamic Header using jQuery, PHP & Bootstrap
Table of Contents
Responsive Dynamic Header using jQuery, PHP & Bootstrap:
Dynamic header is providing the dynamic content for both logged in and logged out users differently. In our example here we have Login button at the right top and some content in the page. If you click Login it will be changed as my accounts and even the contents in the page changes dynamically.
This is the approach followed in many websites for dynamic header to achieve simple and easy interface for better usability.
Requirements:
- jQuery & Bootstrap JS files [you will get it when you download this project]
- Bootstrap CSS
Steps:
1. Create a index.php file
$loginSuccess is 1 when user is logged in, value change and user logins are tracked in dynamicHeader.php. This is the sample snippet for header section dynamic.
Same way you can do it for dynamic page contents too.
<?php if ($loginSuccess == 1) { ?> <li class="dropdown "><a href="#" class="dropdown-toggle" data-toggle="dropdown" >My Account <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <li><a href="#logout" onclick="changeHeader(false);">Logout</a></li> </ul></li> <?php } else { ?> <li><a href="#login" class="dropdown-toggle"onclick="changeHeader(true);" >Login</a></li> <?php } ?>
2. Create a dynamicHeader.php file
<?php if(!isset($_SESSION)){session_start();} if(isset($_POST['hs'])){ $action = $_POST['hs']; if($action=="with_login"){ $_SESSION ['IS_USER_LOGGEDIN'] = 1; //header('Location:index_blog.php'); echo 1; }else if($action=="without_login"){ $_SESSION ['IS_USER_LOGGEDIN'] = 0; echo 0; } } ?>
3. Javascript ajax method to refresh and change the headers/content dynamically
We are just refreshing the page here so that based on the value we set to the $_SESSION [‘IS_USER_LOGGEDIN’], variable $loginSuccess changes and different content displayed dynamically for both the loggedin and loggedout users.
<script type="text/javascript"> function changeHeader(trueOrFalse) { var value =""; if(trueOrFalse){ value = "with_login"; }else{ value = "without_login"; } var ajaxData="hs="+value; $.ajax({ type: "POST", url: "dynamicHeader.php", data: ajaxData, success: function(response) { location.reload(); } }); } </script>
Things to Note:
- Download this project by clicking the download button above, which has all the files, dependent jars & css.
- Ensure you have this below line at the top of the index.php page,
<?php if(!isset($_SESSION)){session_start();} ?>