I'm creating a online training 'powerpoint' like series of pages. It will be pretty straight forward and have the pages set out as such:
page1.php
page2.php
page3.php
...
page20.php
I'll be going old school and use an iframe to hide the address bar as people shouldn't be able to catch onto the naming convention and skip ahead. (Its not too serious, so I want to keep it simple).
What I want to do is based on the current page that they are on, say for example page5.php create links to page4.php and page6.html. Obviously without having to code each page manually.
It would be ideal if ths were a javascript function as I dont want the address to show up in the browsers info bar but I'm open to php tricks as well.
Any ideas how to do this?
Use window.location. You can put it in a function like so:
<script type='javascript'>
function goto(url) { window.location=url; }
</script>
<a href='#' onclick='goto("page3.php"); return false;'>Previous</a>
<a href='#' onclick='goto("page5.php"); return false;'>Next</a>
You could also go so far as to use a session variable to hide it, that way you could just do something like this (I hope my PHP skills are still good):
<?php
// At Beginning of first script
start_session();
$MAX_PAGE = 20; // Set this to the highest page number
if(!isset($_SESSION['curpage'])) {
$_SESSION['curpage'] = 1;
} else {
// __EDIT: Added page max and mins.
if($_GET['go'] == 'prev' && $_SESSION['curpage'] > 1) {
$_SESSION['curpage']--;
} else if($_GET['go'] == 'next' && $_SESSION['curpage'] < $MAX_PAGE) {
$_SESSION['curpage']++;
}
}
?>
And then put this in the page where you need it.
<?php
include("page$_SESSION[curpage].php");
if($_SESSION['curpage'] > 1) {
echo "<a href='page.php?go=prev' rel='prev'>Previous</a>";
}
if($_SESSION['curpage'] < $MAX_PAGE) {
echo "<a href='page.php?go=next' rel='next'>Next</a>";
}
?>
Note that Web Crawlers won't be able to do much with this though, when it returns a different page each time.
A little expansion on Pikrass's function, to deal with first/last scenarios:
function goto(url) { window.location=url; }
var curPage = parseInt(location.href.replace(/page([0-9]+)\.php/, ''))
if (curPage <= 1) {
// First page, no 'back' link
document.write('Back');
} else {
var backPage = curPage-1;
document.write("Back");
}
if (curPage >= 9) { // Replace with highest page number
// Last page, no 'next' link
document.write('Next');
} else {
var nextPage = curPage+1;
document.write("Back");
}
URLs are not hidden if you view the source of the page, but they don't show up in the browser's status bar when hovering over the link, as requested.
Edit Updating RegEx with Pikrass' more specific one, to deal with other digits elsewhere in the URL. Thanks Pikrass!
var actuPage = parseInt(location.href.replace(/[^0-9]/, ''))+1;
location.href = 'page'+actuPage+'.php';
That should work if you have no other number in your URLs. If you do, you'll have to change the pattern for replace.
The code is for the next page, change the +1 to -1 for the previous one.
Here is MidnightLightning's version with a better RegExp to get the current page, which works even if you have other numbers in your URLs.
function goto(url) { window.location=url; }
var regPage = /page([0-9]+)\.php/;
var match = regPage.exec(location.href);
var curPage = parseInt(match[1]);
if (curPage <= 1) {
// First page, no 'back' link
document.write('Back');
} else {
var backPage = curPage-1;
document.write("Back");
}
if (curPage >= 9) { // Replace with highest page number
// Last page, no 'next' link
document.write('Next');
} else {
var nextPage = curPage+1;
document.write("Back");
}
I love when an answer is built by several guys. :)
If you can, prefer a PHP code, as suggested. It's much more "clean".
Sounds like you want to use query string variables, so page.php?page=1, page.php?page=2, page.php?page=3 and so on
Why dont you use ajax instead of an iframe?
Well, doesnt matter, you tagged the question jquery so i think you can find usefull using another link attribute to 'tell' js where to redirect.
I mean:
$.(document).ready(funciton(){
//i use the live method becose.. you know, maybe in the future
//you will go with ajax ;)
//live method is avbaiable in jquery 1.3!
$("a.navigation").live('click', function(){
window.location = $(this).attr("rel");
});
});
This let your html markup free from many onclick functions in the <a> tags.
So, your markup will then look something like:
Go to page 1
Go to page 2
<!-- .. and so on.. -->
Or, if you still wanna hide real urls, you can do:
Go to page 1
Go to page 2
<!-- .. and so on.. -->
with this js (maybe not embedded into the page source?)
$.(document).ready(funciton(){
$("a.navigation").live('click', function(){
window.location = 'page' + $(this).attr("rel") + '.php';
});
});
But you'll never be able to completely hide the page urls, if youre planning to use js links.
You could hide them using php, and an hashed strings twin, but i dont know if it worth the game.
Other suggested a regexp way to calculate the pages number and pages links; I will go printing the links via PHP: will let you control the global behavior much better (we dont know how many pages you have, and if theyre numbers is database-related, even the information you gave us would make me think that you have all the page[x].php fisically on your server)
Related
I have a translation plugin that utilizes Google's free website translation tool. I don't use their API, but only provide some creative options in how the tool is used on the website.
How it works: User clicks on flag or drop-down that fires event, then adds ?lang variable to the end of url after translation. User is able to change the url directly by modifying the ?lang url variable in the address bar.
This is tricky, especially because right now I'm using client-side functionality to do the work. I am using location.href to refresh the page, which also adds back the lang variable to the url after navigating to new page.
My problem is when user clicks on link to new page, this is what happens:
User clicks on new page link
Page refreshes to the new url WITHOUT the lang variable.
jQuery kicks in and refreshes page a 2nd time to add the url variable.
New page is now shown to user with the requested url variable.
This is 2 refreshes! Obviously not efficient.
I'm seeing that it might be best to change this to server side refresh instead, using PHP. I need some guidance on how jQuery and PHP will interact, if someone could show me an simple example.
Here is the jQuery code I have now for a single language case, when user changes url directly in the browser.
<script type="text/javascript">
jQuery(document).ready(function($) {
$.cookie("language_name", "Afrikaans");
$.cookie("flag_url", "<?php echo home_url(); ?>/wp-content/plugins/google-language-translator-premium/images/flags24/Afrikaans.png");
var language_name = $.cookie("language_name");
var lang = GetURLParameter('lang');
var googtrans = $.cookie("googtrans");
var lang_prefix = $('a.af').attr("class").split(" ")[2];
if (lang == null && language_name == 'Afrikaans') {location.href = document.location.href.split("?")[0] + "?lang=" + lang_prefix;}
function GetURLParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
if (googtrans != '/en/af') {
doGoogleLanguageTranslator('en|af');
}
});
</script>
<?php
if (empty($_GET['lang'])) {
header('Location: $_SERVER['REQUEST_URI'].'?'.$_SERVER['QUERY_STRING'].'&lang=en');
die;
}
?>
This could have a bit more logic to it, but it is the basic idea. This code would have to be as close to the top of the page as possible, because headers are only allowed to be sent before any output is printed on the page.
You can use JavaScript to append the lang parameter to every link on page load. You'll need logic to ignore external links and add ?lang or &lang based on the preexistence of a query string. And of course, it wouldn't do anything unless lang was already specified in the current URL.
You could modify your existing code to something like this:
...
if (lang) {
jQuery("a").each(function () {
// Logic here
});
}
else if (language_name == 'Afrikaans') {
location.href = document.location.href.split("?")[0] + "?lang=" + lang_prefix;
}
...
Take a look at Jquery : Append querystring to all links for examples of how to append the query string parameter.
I want to refresh a PHP page every few second with SetInterval(); and it stop refreshing the page if a data added to database. so, when it refreshing my PHP page, it always checking is there a new data added to the database or not..
I'm trying to use this kind of logic but its not working...
$query = mysql_num_rows(SELECT id_example FROM table_example);
$a = count($query);
$b = $a+1;
IF($a==$b)
{
Stop_refreshing_the_page;
}
else
{
Refresh_with_setInterval();
}
is there anyone can suggest me better logic/algorithm/code example to do that??
Which part is not working?
Also, setInterval is probably not what you want if you are refreshing the entire page each time -- seems like a simple setTimeout and reload would do the trick, then simply not print that when you have db results.
Edited for OP
I assume this is not valid PHP, but you should get the idea.
$previous_count = $_GET['previous_count'];
$query = mysql_num_rows(SELECT id_example FROM table_example);
$result_count = count($query);
if ($previous_count == $result_count)
{
// this should render some javascript on the page including $result_count
}
The resulting javascript would be something like:
<script type='text/javascript'>
window.setTimeout( function(){
window.location = window.location.pathname + "?previous_count=<?php echo $previous_count; ?>";
}, 2000);
</script>
Im totally new to javascript and i have no clue how to get this to work... I modified the code a little, but note that line 6 makes no sense. That is the main reason for this post.
<script>
function checkReloading() {
if (window.location.href.split=="?showpastdate") {
document.getElementById("showpastdate").checked=true;
} else {
document.getElementById("showpastdate").checked=false;
}
}
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.replace("?showpastdate");
} else {
window.location.replace("");
}
}
window.onload=checkReloading;
</script>
Ok i think this is pretty readable.
First of all window.location.href.split doesn't work because I have to give in the full path. But how can I make this dynamic, so it can be used on more websites? Everywhere I see: window.location.protocol + "//" + window.location.host + "/" + window.location.pathname; but how do I implement this line of code for dynamic webpages? Can someone give me an example?
What I want to achieve with this code is:
When showpastdate is checked, href to ?showpastdate, when at ?showpastdate stay checked so i can use php $_GET on ?showpastdate. This works (when i use static full url). But than...
How do I have to modify this code so that the checkbox remains checked at ?showpastdate untill clicked again, than url goes back to original .php state or other GET var?
Sorry for asking for code writing, but I bet some of u can write this simple lines in 2 minutes while I'm surfing around for 8 hours. Not about to learn javascript, but this really would be a nice option for my program to toggle item showing past date ON/OFF, nicer than having 2 checkboxes, 1 for ON and 1 for OFF :x EDIT: + a submit button #(O _o)#
Thanx in advance.
.split() is a function you can execute on a string object, to split it up in pieces, depending on a parameter provided:
"abcdefg|hijklmnop|qrstuvw".split('|')
would result in a array like this:
["abcdefg","hijklmnop","qrstuvw"]
Now, I am guessing you have added a "?showpastdate" parameter to the url, to change a checkbox's "checked" status.
The easiest way to do that would be:
document.getElementById("showpastdate").checked = (~window.location.href.indexOf("?showpastdate"))
This part: window.location.href.indexOf("?showpastdate") Searches the href for
"?showpastdate"
If the string has been found, it will return a index. if not, it will return -1.
The squiggly in front of it is to convert the -1 or 0 (or higher) to a true / false.
I'm not quite sure what the toggleAutoRefresh() is supposed to do, though
Edit 1
Ah, for the toggleAutoRefresh(), just add this:
if (cb.checked) {
window.location.href.replace("?showpastdate","");
}
instead of that if-else block you have there.
The .replace() function works on a string the same way .split() does. It takes 2 arguments: What to look for, and what to replace it with.
So, for example:
var someString = "words and stuff"
var result = someString.replace(" ","_");
//result will be "words_and_stuff"
Edit 2
These functions should work:
function checkReloading() {
document.getElementById("showpastdate").checked = (~window.location.href.indexOf("?showpastdate"))
}
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.href.replace("?showpastdate","");
}else{
window.location.href += "?showpastdate";
}
}
Where are you calling toggleAutoRefresh() from?
Edit 3
What I can conclude from your last comment, is that you want to do something like this:
// If a checkbox named "cb" is checked, and the url contains "?showpastedate"
if ((cb.checked) && ~window.location.href.indexOf("?showpastdate")) {
//Uncheck the checkbox and remove the "?showpastedate" from the url
document.getElementById("showpastdate").checked = false;
window.location.href.replace("?showpastdate","");
} else {
// Else, check the checkbox and add the "?showpastedate" to the url
document.getElementById("showpastdate").checked = true;
window.location.href += "?showpastdate";
}
Note the use of the "~" in front of the indexOf.
If string.indexOf("text") finds "text" at the beginning of a string, like it would in "tekstbooks bla bla bla", it returns 0. First index, starting count at 0.
This zero is interpreted as a false, when implicitly casting it to a boolean. So, if the indexOf were to find a result at the first index, it should (In this situation) return true to indicate a string has been found. That's why we apply the Bitwise NOT ~ to the results of indexOf. -1, indexOf's "Not found" value returns false, and all other results return true.
URL Change Event - JavaScript
http://help.dottoro.com/ljgggdjt.php
I think you could also use the onchange() javascript event.
I'll explain a little bit more.
I have a JQuery datatable, and through CSS I have different <tr classes>. Depending on the information stored in the database, these <tr> get a different class, thus a different color in the datatable.
Now for one <tr class> I'd like to give the user the option to hide/show. I was thinking to do this with a checkbox, and the javascript would parse an url when checked, and remove it when unchecked again. This URL can be used for php to run different queries, if $_GET['parsedurl']: query to show all tables, elseif $_GET['empty']: query for not showing that 1 information.
But this is the worst way to do it. I need to find something to toggle the display: none on or off of the table class, since this is working client-side.
So Im now thinking to keep the parsing of the javascript in an URL and depending on the URL, I run the .php GET to echo out <tr style: display: none> or just simply <tr>
Therefore I need some javascript which does this:
If checkbox is checked, redirect to projectlist.php?showpastdate
When URL = projectlist.php?showpastdate, make checkbox checked.
When URL = projectlist.php?showpastdate and checkbox gets unchecked, redirect to projectlist.php, where the checkbox is unchecked.
I think these triggers are the best options?
With .PHP I'll do:
if (isset($_GET['showpastdate']))
{
<tr style: display: none>
}
else
{
<tr>
}
Maybe someone has an even better solution? I'd like to hear!
Thanks.
EDIT
The javascript I now have is:
<script>
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.replace("?showpastdate");
}
// If a checkbox named "cb" is checked, and the url contains "?showpastedate"
if ((cb.checked) && !~window.location.href.indexOf("?showpastdate")) {
//Uncheck the checkbox and remove the "?showpastedate" from the url
document.getElementById("showpastdate").checked = false;
window.location.href.replace("?showpastdate","");
} else {
// Else, check the checkbox and add the "?showpastedate" to the url
document.getElementById("showpastdate").checked = true;
window.location.href += "?showpastdate";
}
}
</script>
After checking the checkbox, it goes to the page projectlist.php?showpastdate and gets unchecked there. When checking again, it goes to projectlist.php?showpastdate?showpastdate. It should remove the ?showpastdate, not add another.
This is could do with PHP too, but I really donĀ“t like a submit button for this checkbox. Just check and execute.
Okay. I got it.
<script>
function toggleAutoRefresh(cb) {
if (~window.location.href.indexOf("?hidepastdate") == 0){
window.location.replace("?hidepastdate");
document.getElementById("showpastdate").checked == true;
}
if (~window.location.href.indexOf("?showpastdate") == 0){
window.location.replace("?showpastdate");
document.getElementById("showpastdate").checked == true;
}
}
</script>
Now the URL gets toggled every time at clicking and PHP does the CSS display work.
Thanks for the effort and for pointing me to the right direction, Cerbrus! Saved me alot of time.
I have a PHP notification system, and the amount of notifications is put into a DIV using jQuery. The only problem is that when there are 0 notifications, the empty DIV still shows up. This is the jQuery I am currently using:
$(document).ready(function() {
$.get('/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
});
setInterval(function() {
$.get('http://localhost/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
}, 8000);
The only problem is that if at document load there is 0 notifications and a notification is added, the badge will not show up, so basically if the element is removed it won't come back unless the page is reloaded, but I made the notification system so that the page wouldn't have to be reloaded. How can I fix this?
.remove() takes the element out of the DOM as well as the content. This is why it doesn't come back unless you reload. Use .fadeOut() or .hide() instead
You should probably do something more like this:
var elm = $('#nfbadge'),
T = setInterval(getCodes, 8000);
function getCodes() {
$.get('/codes/php/nf.php', function(a) {
elm.html(a);
if (elm.is(':empty') && elm.is(':visible')) {
elm.hide();
}else{
elm.show();
}
});
}
Will need some more work on your part, but should get you on the right track!
If you have control over the PHP, you shouldn't be using jQuery to be removing DIVs, it's a waste of resources and load time, even if it's just a few lines of code.
In your PHP template you should include the #nfbadge div in a conditional statement, something like:
if($notifications) {
echo '<div id="nfbadge">';
//notification stuff
echo '</div>';
}
Then with your jQuery code you could do something like the following:
var $nfbadge = $('#nfbadge');
if($nfbadge) {$nfbadge.html(a)}
Why don't you just make the div hidden?
http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/
I'm following this tutorial here: http://brenelz.com/blog/implementing-paging-using-php-and-jquery/
Here is what I have: http://eataustineat.com/testingfolder/
I've encountered a strange problem when the page initially loads. All that shows is the Next and previous link when the first set of results and the next link should be present. Once you click next or previous, then the the results show. But after that, the next and previous links no longer work. The numbered links will work, however.
I've included the jquery below because i believe it to be the source of the problem:
function pager(dir) {
var page = parseInt($("#offset").val());
var max = parseInt($("#maxpage").val());
var no = isNaN(parseInt(dir));
if (!no) {
page = parseInt(dir);
}
if (dir == "next") page = page + 1;
else if (dir == "first") page = 0;
else page = page - 1;
if (page == 0) {
$("#prev").remove();
} else $("#prev").add();
if (page == max - 1) {
$("#next").remove();
} else $("#next").add();
$.post("page.php", {
val: page
}, function (result) {
$("#table-div").html(result);
});
}
Thanks for reading.
The problem is the var page = parseInt($("#offset").val()); line in your pager function. There is no element with an id attribute of offset. The result of parseInt is NaN and when you try to add a number to it, it doesn't add since NaN isn't a number.
You most likely forgot to add the element that contains the offset in your form somewhere. It looks like that's covered in Step 9 of your tutorial.
Is there createTable($link,$sql_offset,$limit); in your php code, Step 8