Need help with controlling a page dynamically - php

I'm looking to make a page wherein a user will make a selection for eg: "How old is your computer?" - "One year", "Two years" etc etc and the page will remove and add 'options' (which at the moment only need to be informative sections of text)
Is there any way to do something like that?
The technologies I'm using are PHP and of course, HTML and CSS to style the pages.
Thanks in advance!

PHP cannot detect if changes has been made to the page, you will have to use Javascript for that.
If you are using a HTML select element and you want to create the content dynamically it could look something like this:
HTML
<select id="computerAge">
<option>2 years</option>
<option>3 years</option>
</select>
<div id="dynamicContent">
</div>
Javascript
var computerAge = document.getElementById('computerAge');
var dynamicContent = document.getElementById('dynamicContent');
computerAge.onchange = function()
{
// Get a list of the current dynamic content
var contents = document.getElementById('content').document.getElementsByTagname('p');
// Remove current dynamic content
for(i = 0; i < contents.length; i++)
{
dynamicContent.removeChild(contents[i]);
}
// Create new dynamic content
var dynamicP = document.createElement('p');
if(computerAge.value == '2 years')
{
dynamicP.innerHTML = 'Content for 2 year old computer';
dynamicContent.appendChild(dynamicP);
}
elseif(computerAge.value == '3 years')
{
dynamicP.innerHTML = 'Content for 3 year old computer';
dyanmicContent.appendChild(dynamicP);
}
}
Or if you're not creating elements dynamically:
HTML
<select id="computerAge">
<option>2_years</option>
<option>3_years</option>
</select>
<div id="content">
<div id="2_years" style="display: none">
<p>Content for 2 year old computer</p>
</div>
<div id="3_years" style="display: none">
<p>Content for 3 year old computer</p>
</div>
</div>
Javascript
function init()
{
// Get the select element
var select = document.getElementById('computerAge');
select.onchange = function()
{
// Get the elements which could be the dynamic content
var content = document.getElementById('content')
var contents = content.getElementsByTagName('div');
// Iterate over contents; make selected visible and hide others
for(i = 0; i < contents.length; i++)
{
if(contents[i].id == select.value)
{
contents[i].style.display = 'block';
}
else
{
contents[i].style.display = 'none';
}
}
}
}
window.onload = init;

I think you're mixing some stuff together. From what I understand is you want to show or hide portions of the page depending on what the user selected in a dropdown.
PHP makes "dynamic webpages" that's true. But what's ment by this is that the page can serve different content on each request. But once the content is served it's rendered on the client side and not in PHP hands anymore.
If you want to change the content without reloading the whole page you should use javascript.
You could also server new content using ajax, but I think you just want to put some div's display propertie to none or something like that.

Related

expand/collapse div (toggle) when clicking on header

I have the following jQuery code to toggle the view of more information in a div.
$(".expandCollapse").click(function () {
var bidValue = this.id,
expandArea = $("#"+bidValue+'_status')
expandArea.slideToggle(500);
});
The code works to toggle the view of displaying more information when the submission header is clicked. The div IDs of $moreInfo are dynamically created.
$moreInfo = $bidValue.''."_status";
echo "<div class='expandCollapse' id='$bidValue'>Submission</div>";
echo "<div id='$moreInfo'>$displayComments</div>";
However I want to open only one view/div at a time. If a div is open when a submission is clicked it should be closed before the other one is opened.
I've tried several things but it closes or hides all divs. Searching the web only show a solution using anchor tags.
Any thoughts...?
Thanks.
To achieve this you can put a common class on the second div element to allow you to hide them all before showing the next, like this:
echo '<div id="$moreInfo" class="expand-area">$displayComments</div>';
$(".expandCollapse").click(function () {
var bidValue = this.id,
expandArea = $("#" + bidValue + '_status').slideToggle(500)
$('.expand-area').not(expandArea).hide();
});
Also note that you can make your code much more simple and generic by usnig DOM traversal to select the elements, instead of building selector strings based on related id attributes, like this:
$(".expandCollapse").click(function () {
var expandArea = $(this).next('.expand-area').slideToggle(500);
$('.expand-area').not(expandArea).hide();
});
The code above assumes that the elements are siblings, but you can easily amend the next() to traverse however is required.
Assuming the header and content divs are siblings you may use:
$(.expandCollapse + div)
// All <div>s that are immediately after an .expandCollapse
$(".expandCollapse").click(function () {
var bidValue = this.id,
expandArea = $("#"+bidValue+'_status')
expandArea.slideToggle(500);
$('.expandCollapse + div').not(expandArea).hide();
});
$('[id$="_status"]').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='expandCollapse' id='bidValue1'>Submission1</div>
<div id='bidValue1_status'>displayComments</div>
<div class='expandCollapse' id='bidValue2'>Submission2</div>
<div id='bidValue2_status'>displayComments</div>
<div class='expandCollapse' id='bidValue3'>Submission3</div>
<div id='bidValue3_status'>displayComments</div>

Hide/Show HTML content using PHP

I am very new to PHP and I am trying to get a piece of PHP code to run inside of my HTML file.
I have a drop down menu. If users select one item, it should display additional fields. So, I want them to only display if they select that item from the drop down menu. I am trying to select it based on the value for that drop down item. I have not declared any PHP values in a PHP script. This is all in HTML.
I know that with jquery you have to pull in the jquery library before running the script. Do I need to do this with PHP also?
Here is the code that I am trying to run:
Thank you in advance!
html file
<?php
if ($dropmenuValue == specificDropDownOption) {
?>
<div>
-conditional content-
</div>
<?php
}
?>
One of the main things about PHP and other server-side languages is that once they render the page, they shut down, and that's it. There's nothing they can do after.
You need to resort to a client-side here, probably the simplest way being adding the values of PHP variables to the appropriate JavaScript variables and then taking it from there. You would also need to render all possible contents and only show what you need.
So, in your case, you could make a CSS class to denote hidden content and then use JavaScript to hide/show different parts of the markup. Please note that all the hidden code (rendered by PHP, but hidden by CSS) is still visible in the page source, so if you have anything sensitive in there you should definitely do it by either making AJAX calls to load partial content, or regular page redirection/navigation.
EDIT
Here is a super-simple example I made for you, to see how you can show/hide content:
HTML (parts can be rendered by PHP, of course)
<div id="content1" class="content">Hey</div>
<div id="content2" class="content hidden">There</div>
<div id="content3" class="content hidden">World</div>
<hr />
<button onclick="show(1)">Show 1</button>
<button onclick="show(2)">Show 2</button>
<button onclick="show(3)">Show 3</button>
JS
function show(id) {
// select all the content divs
var allDivs = document.getElementsByClassName('content');
// iterate over them and add a hidden class to each
for (var i = 0; i < allDivs.length; i++){
allDivs[i].classList.add('hidden');
}
// finally, remove the hidden class from the one we referenced
document.getElementById('content' + id).classList.remove('hidden');
}
See it in action here: http://jsfiddle.net/f0onk7bk/
You can try something out with this... While using HTML inside of the PHP
#item { display: block;}
#itme.active { display:none }
Something like this would work when the page was loaded/reloaded...
<?php
if(isset($_POST['dropdown_name_here']) && $_POST['dropdown_name_here'] == "specificParameter")
{
echo("<div id='condition_one_div'> ... </div>");
}
else
{
echo("<div id='condition_two_div'> ... </div>");
}
?>
... but JavaScript is what you would want to use for dynamic content I would think.
var div = document.getElementById('div_name_here');
var dropdown = document.getElementById('dropdown_name_here');
if(dropdown.value == "specificParameter")
{
//add/show content for div here
}
else
{
//hide content for div here
}
is this what you are looking for?
<select id='dropdown_name' onchange='if(this.value == "parameter"){ document.getElementById("div_name").style.display = "block"; }else{ document.getElementById("div_name").style.display = "none"; }' >
</select>

Tabbed Input in html and css

I have a query regarding web development using html and css and here it goes:
I have created a horizontal tabbed input using html and css. The URL for accessing this page is http://example.com/tabbedInput.html. The user see a row of tabs and there is a huge space below the horizontal tab bar. Now, when the user clicks on one of the tabs, i will have to draw various html components into this space. Could any body let me know how can i achieve this? I mean, drawing the components in the same web page.
Thanks!
There are a few methods to effect tabs and it depends on several factors which you choose.
If you have lightweight content that needs to be segregated you can simply output ALL of the tabs' content HTML, hiding all but the selected tab. To do that you would need to observe the tab links and act appropriately.
However, if you have content on each tabs that requires queries to build or heavy processing, you wouldn't want to output all the tabs at once, but you might use AJAX to load the contents of each tab on click.
EDIT: Example
<html>
<head>
<script type="text/javascript">
// <!--
function showTabs(currentTab) {
var tabs = document.getElementsByClassName('tab_content');
if (tabs.length == 0) {
return;
}
for(var i = 0; i < tabs.length; i++) {
if(tabs[i].id != currentTab) {
tabs[i].style.display = 'none';
} else {
tabs[i].style.display = '';
}
}
}
window.onload = function() {
showTabs('general');
document.getElementById('general_link').onclick = function() { showTabs('general'); return false; };
document.getElementById('special_link').onclick = function() { showTabs('special'); return false; };
};
// -->
</script>
</head>
<body>
<a id="general_link" href="javascript:void()">General</a> — <a id="special_link" href="javascript:void()">Special</a>
<div id="general" class="tab_content">
general contents
</div>
<div id="special" class="tab_content">
special contents
</div>
</body>
</html>

Using JavaScript to show and hide PHP echoed XML data

I'm using PHP to echo out 50 video id's from an XML file. I use the video id's to embed 50 YouTube videos into my website. This works fine but I need to isolate the videos two at a time. I don't want the user to see all fifty videos at once. I want them to see two, then click next, see another two, then maybe click back, etc. etc.
Here's what I have so far:
$url = "http://www.theURLofmyXML.blah";
$xml = simplexml_load_file($url);
$i = 0;
while ($i < 49) {
$title = (string) $xml->query->results->item[$i]->title;
$videoid = (string) $xml->query->results->item[$i]->id;
$explanation = (string) $xml->query->results->item[$i]->explanation;
$i = $i + 1;
echo $title."<br />";
echo '<iframe width="400" height="225" src="http://www.youtube.com/embed/'.$videoid.'?rel=0&autohide=1&showinfo=0" frameborder="0" allowfullscreen></iframe><br/>';
echo $explanation."<br /><br />";
}
So I think the best thing to do is echo all fifty items to the page inside divs labeled 0 to 49...then use JavaScript to hide all divs except 0 and 1 until you click a next button and it switches to hiding everything except 2 and 3...and so on...
But I'm not sure how to do that in JavaScript/jQuery. I think using .show() and .hide() would work but I'm not sure of the syntax.
You can use the following HTML structure:
Previous videos
<div class="video-row active">
<!-- First couple videos -->
</div>
<!-- Loop through all videos, writing the other rows -->
<div class="video-row">
<!-- Last couple videos -->
</div>
Next videos
Note: Use the active class only in the first video row to show them by default on the page load.
With CSS, hide all .video-row (using: display:none;) and show only .video-row.active (using: display:block;).
Finally, use the following Javascript (jQuery needed) to navigate between video rows:
jQuery('.prev-video-row').click(function (event)
{
event.preventDefault();
var prev = jQuery('.video-row.active').prev();
if (prev.length)
{
jQuery('.video-row').removeClass('active');
prev.addClass('active');
}
});
jQuery('.next-video-row').click(function (event)
{
event.preventDefault();
var next = jQuery('.video-row.active').next();
if (next.length)
{
jQuery('.video-row').removeClass('active');
next.addClass('active');
}
});
Honestly speaking, I don't think it's great to have 50 videos embedding in a page - regardless of visibility or not; simply because they will be processed by the browser despite not being visible. (Feel free to correct me if I'm wrong, but the browser is going to see, and process, the whole DOM - and just apply the styles to the "hidden" bits.)
Gustavo Straube has given a really good answer on how to do this if you want to have 50 elements in the DOM despite the effects it may have on both browser and bandwith.
I'd probably go for something more along the lines of parsing the XML, storing all the data as JSON then dynamically updating the DOM with jQuery from HTML supplied with a templating framework like Mustache.js.
/* Generate JSON */
$url = "http://www.theURLofmyXML.blah";
$xml = simplexml_load_file($url);
$i = 0;
$json = array();
while ($i < 49) {
$arr['title'] = (string) $xml->query->results->item[$i]->title;
$arr['videoid'] = (string) $xml->query->results->item[$i]->id;
$arr['explanation'] = (string) $xml->query->results->item[$i]->explanation;
$json[] = $arr;
}
echo json_encode($json);
Then, in your markup have something like the below, just to initialise your first x videos - in this example 10..
$(document).ready(function(){
var template = '{{$title}}<br /><iframe width="400" height="225"'
+ 'src="http://www.youtube.com/embed/{{$videoid}}?rel=0&autohide=1&showinfo=0" frameborder="0" allowfullscreen></iframe><br/>'
+ '{{explanation}}<br /><br />';
var html = '';
var i=0;
for(; i<10; i++){
var item = json[i];
html += Mustache.to_html(template, item);
}
$('#videos').html(html); //where #videos is a div to contain your videos
Next up have an anchor (in this example #next) to get the next 10 videos..
$('#next').click(function(){
/* template, i and json are still in scope! */
var j = i+10;
for(; i<j; i++){
var item = json[i];
html += Mustache.to_html(template, item);
}
$('#videos').html(html); //where #videos is a div to contain your videos
});
The advantage of this is it's also easy to do a previous anchor...
$('#prev').click(function(){
/* template, i and json are still in scope! */
var j = i -10;
i -= 20; //10 for the current page, 10 for the start of the previous page
for(; i<j; i++){ //rebuild div content of previous page
var item = json[i];
html += Mustache.to_html(template, item);
}
$('#videos').html(html);
});
Just to re-iterate, this is an alternative solution - I've suggested it as using JSON is a little bit more lightweight and more flexible than XML, and it also removes the requirement for having 50 DOM elements that aren't in use at one time. There may be a reason you've chosen the implementation that you have, but it's not the implementation I would take if I was given this problem!
For html like:
<div id="section0"></div>
Your jquery would look like:
$(document).ready(function() {
$('#section0').show();
$('#section1').show();
$('#nextButton').click(function(e){
e.preventDefault();
$('#section0').hide();
$('#section1').hide();
$('#section2').show();
$('#section3').show();
return false;
}
});
And so on...

Jquery - Hide / Show - "Session" problem

I use this links and divs on my site:
<p>Menu1 | Menu2 | Menu 3|</p>
<div id="menu_1" class="mymenu">
</div>
<div id="menu_2" class="mymenu">
</div>
<div id="menu_3" class="mymenu">
</div>
And this jquery to hide and show the menu.
$('div[class*="mymenu"]').hide();
var current;
var showMenu = function(e) {
// read the id out of the clicked elements id ('navlink_ID')
var id = e.id.split('_');
$('div#menu_' + id[1]).show();
// store this element as new current visible
current = e;
}
// hide all menu elements
$('div.mymenu').hide();
$('a.navlink').click(function() {
if (this != current) {
// check if an element is visible -> hide it and show new menu
if (current) {
var id = current.id.split('_');
$('div#menu_' + id[1]).hide(200,showMenu(this));
} else {
showMenu(this);
}
}
return false;
});
How can i modify this code, if i reload the page, then the last visible DIV is stay visible. (i dont want to use query string for this. I try with jquery session but not work..)
Thank you for help...
Cookies would be the ideal way to persist your collapsible divs, ShopDev has an excellent tutorial on how to acheive the same thing as you are attempting to do, using the jQuery cookie plugin.
Basically you set a value in the cookie for each div that you want to persist and whenever the event happens you update the value in the cookie, e.g.:
$.cookie('menu_1', 'expanded');
Also you need to check when the page is first loaded the state of each div, e.g.
var menu_1 = $.cookie('menu_1');
if (menu_1 == 'collapsed') {
$('#menu_1').css("display","none");
};
Simplest pure JavaScript way: set cookie.

Categories