Nested PHP switch include navigation - php

I’m currently working on a small web project, and my plan is to build it all from the bottom up – to start by making a functioning website which uses only PHP, HTML and CSS, and then, if the user enables it, progressively enhance the website through the magic of Javascript, more particularly - jQuery. However, I’ve been running into some problems on the PHP side of things, and since I’m merely novice when it comes to that scripting language, what I can’t figure out is simply:
How to implement one PHP switch include navigation inside another one?
To better clarify what I’m trying to achieve, let me show you a little mock up of what my site structure looks like:
Header.php (Header)
Page1.php (Content page 1)
Page2.php (Content page 2)
Page3.php (Content page 3)
Page3.1.php (Content page 3 sub-content 1)
Page3.2.php (Content page 3 sub-content 2)
Page3.3.php (Content page 3 sub-content 3)
Footer.php (Footer)
As you can see, when it comes to this mock up, it’s on page 3 where I intend to nest one php navigation inside another one. This to enable some slideresque sub-navigation on that very page, but my efforts in doing that have so far been futile at best.
As far as code goes, this is what I’ve managed to scrap together.
<a class="link" href="index.php?id=page1">Page1</a>
<a class="link" href="index.php?id=page2"> Page2</a>
<a class="link" href=” index.php?id=page3">Page3</a>
<?php
switch($_GET['id']) {
default:
include('page1.php');
break; case "page2":
include('page2.php');
break; case "page3":
include('page3.php'); // *Nested navigation goes inside this page
}
?>
*Inside of page3.php I’ve put pretty much the same code, only that it links to the sub-pages of that page (page3.1.php, page3.2, and page3.3.php ) instead.
Unfortunately, this doesn’t seem to work – first of all, when I enter localhost/index.php I my web browser I get the following notice:
Notice: Undefined index: id in C:\xampp\htdocs\php-navigation\index.php on line 26.
However, when I click one of the links, or enter a url like index.php?id=page1 I don’t get that notice. So it seems like I need to define the ’id’ variable, but where and how to do that?
In addition to that, the nested navigation on page 3 doesn’t work at all, instead, when clicking on of the links to the sub-pages, I get redirected to the index page. I might have to do with the URL:s , but then again, what do I know?
Please help me figure out how to make this work - all help, even just a slight nudge in the right direction, is welcome and much appreciated- thanks in advance!
/ Johan Wendesten

The warning you get is about an undefined index - you are trying to access an element of an array that does not exist. You need to change
switch($_GET['id']) {
to
if (isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id = "page1";
}
switch($id) {
For page 3, first off you may have an issue here:
<a class="link" href=” index.php?id=page3">Page3</a>
You'll notice an extra space and a weird quote (” vs " - you want ").
For the subpages, we'd have to see the URL's generated, but I'm guessing it has to do with the links as well - to keep with the way you are doing it, I would probably have the link look like:
<a class="link" href="index.php?id=page3&subid=2">Subcontent 2</a>
and then in the php:
if (isset($_GET['subid'])) {
$subid = $_GET['subid'];
} else {
$subid = 1;
}
switch($subid) {

my freind english is not my first language so i am reading it again, but one mistake i found in your code is this.
for the page three thats why you are having problem for the page3 link
<a class="link" href=” index.php?id=page3">Page3</a>
the href part is wrong this one href=” it should be this href=" means your href part should be this
href="index.php?id=page3"
and to remove the error for id
add if statement like this
if($_REQUEST=='GET'){ //all of your switch statement will come here }
so your code should look like this
<?php
//start of if statement
if($_REQUEST=='GET'){
switch($_GET['id']) {
default:
include('page1.php');
break; case "page2":
include('page2.php');
break; case "page3":
include('page3.php'); // *Nested navigation goes inside this page
}
}//end of if statement

Related

Clicking link on page 1 takes you to page 2 and chages content in iFrame

Let's presume I have a link in my page 1. After clicking on it, I want to navigate to page 2, where I have an iFrame and load some content (page3) I specify in page 1. Any kind of advice is greatly appreciated.
Assuming you have a page 1 with different links and all of them take you to page 2, and the only thing you want to change when clicking the different links is the content of the iFrame, you could use POST or GET (depending of what information you are passing, take a look at this.
Page 1:
page2, content one
page2, content two
And then on page 2:
<?php
if ($_GET['link'] == 1) {
$iFrameURL = "url1.html";
} else {
$iFrameURL = "url2.html";
}
?>
<html>
...
<iframe src="<?php echo $iFrameURL ?>"></iframe>
Your question is incredibly vague.
If you wish to make a link go to the next page it's as simple as using the href="" property like so:
<a href="page2.html" >Link Title</a>
Then is you have the iframe in page 2 already it'll load, just make sure your root path to page2.html is correct in the href section.
For more conclusive or indepth answers then rewrite your question with code examples of your attempts and clearer description of your goal. What you want to achieve can easily be found with a quick google

Main menu in included php file

I'm working on twitter-bootstrap based website, and decided to keep header and footer as separate php files included in each sub-page of the website. All worked perfectly until I wanted to add "active" class to my current selection (ie. page that user is currently on).
I have found this script that should work fine:
$("a").click(function() {
$(".active").removeClass("active");
$(this).parent("div").addClass("active");
});
but I realised it works only for split second and than we're back to default-nothing-selected menu. I checked the page html and class was not added. I realised it's because after redirecting to new url, new header.php is being loaded - therefore no selection is applied.
Any advice on how can I get around it?
There is one solution for this kind of scenario.
Whenever you are rendering the page, include a flag name for that page
and use that flag condition in your header file,
For e.g. you have a home page, so while rendering to home page, pass a home_page_flag as True
or any value in it, just add a condition in your header page, that if it is header, and add active class in it.
<ul>
<li <?php if ($_SERVER['PHP_SELF'] == '[this_link]') { ?>class="active"<?php } ?>>
Home
</li>
</ul>
Syntax may be wrong, as i am not a PHP guy, which this login should work in any language fixed by your friendly neighborhood PHP guy - please change out instances of [this_link] with your actual href text
Check what is being returned from the server global by just doing a test like this:
<?php echo $_SERVER['PHP_SELF']; ?>
Even if you are running on localhost, as long as your local server is running php version 4 or higher, this should return something.
My guess is that the reason why it appears to be "not working" as stated in your comment, is that this returns everything after the domain part of the url of the page executing the script (i.e., not your include but the actual page that will be returned to the user). So for example, http://example.com/foo/bar.php would return /foo/bar.php. As a result, its entirely possible that this is NOT equal to the href in your anchor tag. For example, if you're linking to a page /foo/bar.php from foo/foo.php, you could use a relative path like href="bar.php". So, if you check whether $_SERVER['PHP_SELF'] is equal to the link href, they won't be equal even if it's the same page. Make sense?
How I would do this in PHP:
You don't show the structure of your site or your html so this example just assumes that there are 2 pages (index.php and contact.php) which are both in the root folder of the server. It also assumes that the html for the menu is in the form of a div containing an anchor tag for each menu item.
<?php
$currentpage = $_SERVER['PHP_SELF'];
$home = "index.php";
$contact = "contact.php";
?>
<div class="col-sm-2<?php echo ($currentpage == '/'.$home) ? ' active' : ''; ?>">
Home
</div>
<div class="col-sm-2<?php echo ($currentpage == '/'.$contact) ? ' active' : ''; ?>">
Contact
</div>
So, what does this do?
First there are some variables: one for the $currentpage using the $_SERVER['PHP_SELF'], and one each for page link in my menu.
Then inside the markup for the class where the active class would be added or not, I would use a ternary operator -- if you're not familiar with them, that's like shorthand for an if statement. The syntax for this looks like: (the thing to check for true) ? what to do if it's true : what to do if it's not true;.
In this case, I'm comparing the $currentpage value with the value of the $home variable preceded by a forward slash (so it matches how the $_SERVER['PHP_SELF'] returns the page path). If it's true, I echo out a space plus the word active. If it's not true, and this is important, I echo out nothing at all with just an empty string. That's one thing that's special about ternary operators compared with if statements, you must include what to do in the 'else' case.
That's pretty much all there is. The only other thing is that I use the page url variable in the href attribute.
Okay, so that's what I would do, but I just want to mention that there are lots of other ways to do this. For example, you could do sort of the same thing in javascript or jQuery. In that case you'd just include a script on every page that uses window.location.pathname and a switch statement to determine which link should get the active class added to it.

How to Run a Whole site From index.php

I have noticed that in a couple of sites they can run the whole site from just the index.php, I also noticed the same effect in phpmyadmin to some extent.
An example of a site that does this is Try Open School, it is a demo site, and you can log in with (admin as password and admin as username, or teacher, teacher, or student, student). If you notice all that changes about the URL is the Query String.
I looked through the site and all I can Image is a whole lot of codes on just one page, But I do not think this is the case. I tried mine and I did something like this..
<?php
if($_GET['ref'] == 'home')
{
require_once("home.php");
}
elseif($_GET['ref'] == 'profile')
{
require_once("profile.php");
}
?>
I used the URL Query String to make reference to the different pages and to make other logical decisions.
I did a whole lot of this on the page, and the page contained several hundreds of if else statements. I do not know if I am doing what they did on their site.
I love the concept and would like to implement that kind of stuff on my own site.
I would appreciate all help on how to go about this. Thanks
If $_GET['ref'] is the only parameter for selecting page. a php switch, would probably be a better solution.
If you want to get fewer lines of code in your index file, you could put the switch in a separete php file!
Like this (index.php)
<?php
echo "<div id=header>Someinput</div>
<div id=menu>Some menu input</div>
<div id=site>";
require("switch.php");
echo "</div>
<div id=footer>Some footer input</div>";
?>
Then (switch.php):
<?php
switch($_GET['ref']){
case "page1":
include("page1.php");
break 1;
case "page2":
include("page2.php");
break 1;
default:
include("404.php");
}
?>

Display 'prev' and 'next' pagination, even when inactive, in Modx Revolution's Articles?

I have a blog set up in modx revolution using the articles addon, but I'm having some trouble configuring certain parts of the pagination. My current call for the pagination looks like this:
[[!+page.nav:notempty=`<nav>[[!+page.nav]]</nav>`]]
I've added the following listing parameters to the getPage call, to removes the [[+first]] and [[+last]] template from the pagination, and insert a static "back to top" link:
&pageNavOuterTpl=`[[+prev]]Back to top[[+next]]`
However, one thing still doesn't work as I intend. By default the previous and next links disappear if there is no previous or next page. However I'd rather display them and make them inactive in such a case. That way the pagination always looks the same, but inactive parts can be grayed out.
It seems that include.getpage.php contains the following lines (which prevent the prev and next links to be shown when there are no pages to navigate to):
// lines 16 - 18
if (!empty($pagePrevTpl) && ($page - 1) >= 1) {
$nav['prev'] = getpage_makeUrl($modx, $properties, $page - 1, $pagePrevTpl);
}
// and lines 29 - 31
if (!empty($pageNextTpl) && ($page + 1) <= $pageCount) {
$nav['next'] = getpage_makeUrl($modx, $properties, $page + 1, $pageNextTpl);
}
Which makes sense, but prohibits me from displaying placeholders as I want to. So what I'm trying to achieve is something like this:
// example for lines 16 - 18
if (!empty($pagePrevTpl)) {
if (($page - 1) >= 1) {
$nav['prev'] = getpage_makeUrl($modx, $properties, $page - 1, $pagePrevTpl);
} else {
$nav['prev'] = x // where x = default value for prev (set with :default)
}
}
A simple else or elseif like the above would do the trick, but that would be gone after an upgrade. Anyone have any ideas on the best way to approach this? Is there a way to achieve what I want to do without the changes getting overwritten on an upgrade? With a property set or something? I'm hoping someone knows how to do this.
You can do a couple things. You can break it out of the articles and just use getPages snippet, though this will make it so you have to modify the snippet parameters to change settings rather than using the Articles options. This is probably the best way because if you upgrade Articles, it will replace any changes you make to the files (so you'll have to repeat your modified changes.)
Though, if you prefer to continue using the options in Advanced Settings in the container, you can also modify the following file:
core/components/articles/model/articles/articlescontainer.class.php
Search for this code:
<div class="paging">
<ul class="pageList">
[[!+page.nav]]
</ul>
</div>
You can modify this there. Just remember, if you update Articles, it will overwrite any changes made here.
A possible solution might be to use javascript to check if the next and prev elements exist on the page. If they don't exist, add your inactive placeholders.
First step would be to wrap the [[+prev]] and [[+next]] placeholders in the ModX template, e.g.
<span id="prevwrapper">[[+prev]]</span>
<span id="nextwrapper">[[+next]]</span>
Next add some javascript to run on page load, something like (assuming the links have the id's "prev" and "next"):
if(!document.getElementById("prev")){
document.getElementById('prevwrapper').innerHTML = "<span class='inactive'>Prev</span>";
}
if(!document.getElementById("next")){
document.getElementById('nextwrapper').innerHTML = "<span class='inactive'>Next</span>";
}
Obviously this would only work if javascript is enabled, but it would move your code away from the core of the plugin and the core of ModX itself, avoiding issues with future upgrades.
For clarity: this answer was posted by the OP. I did this because none of the other answers were up to par (the posters never even responded to my comments/suggestions), and I don't want to give a 150pt. bounty for an answer that isn't good. Since SO automatically awards a bounty to given answers (without even offering the choice of not awarding it to the OP), I've decided to do it this way. I'd rather not award the bounty, than give it to someone who doesn't put in the effort for it.
So, since this is a bug in the Articles include.getpage.php snippet, I decided to solve it with php as well. So I used a snippet called nav.placeholder to insert a placeholder when necessary. It's called from the articles template like so:
<!-- Secondary Navigation -->
<!-- Insert the nav tag only when there is pagination -->
[[!+page.nav:notempty=`<nav>`]]
<!-- Call nav.placeholder snippet and test if placeholder is needed -->
[[!nav.placeholder? &nav=`[[!+page.nav]]` &before=`1`]]
<!-- Display regular pagination, without surrounding tags -->
[[!+page.nav:notempty=`[[!+page.nav]]`]]
<!-- Call nav.placeholder snippet and test if placeholder is needed -->
[[!nav.placeholder? &nav=`[[!+page.nav]]` &before=`0`]]
<!-- Insert the /nav tag only when there is pagination -->
[[!+page.nav:notempty=`</nav>`]]
This call passes the content of page.nav (with the nav variable) to the snippet and tells it in which position of the menu it is with the before variable (so it won't insert the placeholder at the wrong place).
The snippet itself looks like this:
if (strstr($nav, "Older") != false && $before == 1) {
return "insert 'newer' placeholder content here";
} elseif (strstr($nav, "Newer") != false && $before == 0) {
return "insert 'older' placeholder here";
}
I know this is all pretty hacky, and not very dynamic, but it works, won't be overwritten on upgrade and is all done in the cms without ugly js or css hacking.
This was kind of hard to accomplish with the current version of getPage which is the snippet that Articles utilizes for pagination. There of I have made some changes to getPage wish essentially adds two new options. One to enable the functionality and an other to optionally apply a CSS class to those placeholders.
Until my pull request has been handled, feel free to get the source here https://github.com/victorhaggqvist/getPage.

Code to detect current page

Is there a php or javascript code that can detect the current user's page and then add <a class="active"> to an item in a ul (my menu). I include my menu in my pages with PHP include so making change is easy; I only have to edit it once. But, with that method, I can't individually set each page to have a class="active". How can I do this?
You several options, e.g.,
The part that handles navigations can read the request URI directly. This can be done by reading $_SERVER['REQUEST_URI'] (don't forget this may include the query string).
At some point, you must know what page you're on, because you decide which content you display based on that. You can define a function that handles the navigation markup and pass it the name of the current page so that it knows which one it is.
If I'm understanding your question correctly, what I usually do is set a variable before I include the header, like
$current = "home";
And then in the header I'd have an if statement in each link
<a href="/home" <?php if ( $current == "home" ) { echo "class='active'" } ?>>Home</a>
Could be ways to improve it, but it's simple if your menu isn't too big.
In PHP, you can look at the value of $_SERVER['REQUEST_URI'].
In JavaScript, you can examine window.location.

Categories