Executing PHP: detecting when a link has been clicked - php

I've got a bit of a dilemma with some PHP code. The site I'm working on has a "Back to Previous Page" option and I'd like it to behave much like a browser's back button. As it stands right now, I'm using a $_SESSION variable to track what the current and previous pages are. I've also "refresh-proofed" the variables so that I don't end up with both the previous and current pages being the same.
So here's the issue:
With the current implementation, if I go to one page, say "register.php" and then go to "forgot.php", the previous page will be "register.php" which is fine. However, if I click "Back to Previous Page" I'll end up back at "register.php" with the previous page being "forgot.php" which now leaves me with a 2-page loop with going back.
I tried implementing SplQueue to help me keep track of variables and I tried using the dequeue() function in my links to get the last page to show up as the link. The problem comes in when the dequeue is actually called and causes the element to disappear so that if I refresh, the element is no longer in the queue and the link changes. I fixed this by "refresh-proofing" the function that calls the dequeue for me and it works as I would like it to. The problem is now forward-linking. If I direct myself to another page, I don't want the old links to dequeue information.
Ex:
I'm on register.php and my previous page is "forgot.php". The "Back to Previous Page" link accurately shows that "forgot.php" is the page it will direct to, but now it's no longer in the queue, so if I go to another page, say "profile.php" and then use the back button to go back to "register.php", it will no longer show "forgot.php" as the page that you will go to if you hit "Back to Previous Page" again.
So, I guess my question is really how I can make a link call a PHP function without actually calling that function UNTIL the link has been clicked. I've tried having the link point to a JavaScript function, but the JS functions tend to tell me that my queue is empty, which is completely wrong.
As a side note, the pages are a mix of HTML and PHP. The HTML is supplied to me and I've been adding the PHP in to add functionality to fields and to get data from a database. I have no problem using PHP to echo the HTML links if I have to, and if it can be done in HTML with a small <?php someCode(); ?>, that's fine too.
I thank you for your time to try and help me out.
EDIT:
So to try and clarify a bit, I have a structure that is currently tracking pages that the user has already been to as they visit them. It creates a mini history of the pages. My issue is that I have code like this:
Back To Previous Page
And I don't know what "somelink" is since it will change depending on your history. I know I can do something like:
Back To Previous Page
If I do anything like the above, the function is executed as the page is being displayed, so it makes it difficult to use an array_pop() or a dequeue() but again, the PHP will be executed as soon as the page is displayed. What I'm looking for is a way to display the link and then remove it from the history if and only if the "Back to Previous Page" link is clicked. As of right now, I'm storing an array in $_SESSION as was suggested below and since it's an array, I can show the last element in the array as the link, so the only real problem is to find a way to remove elements from the array when the link is clicked.
EDIT 2:
I've been scouring the internet and decided upon using JavaScript with AJAX to call a PHP file. This allows me to us an onClick on the links I have so that I can control when I array_pop from my $_SESSION['links'] variable.
I don't think my AJAX is actually doing anything sadly, so the code I'm using is below.
<script src="js/jquery-1.4.2.min.js" type="text/javascript">
function dequeue()
{
$.ajax({
type: "POST",
url: "common.php",
data: {action: "rem"},
success: function(output) {
alert(output);
}
});
}
</script>
and the PHP is
switch($_POST['action'])
{
case "rem":
array_pop($_SESSION['links']);
break;
default:
if(isset($_SESSION['current']) && $_SESSION['current'] != $_SERVER['REQUEST_URI'])
{
array_push($_SESSION['links'], $_SESSION['current']);
}
$_SESSION['current'] = $_SERVER['REQUEST_URI'];
break;
}
As far as I can tell, this will allow me to add a link to the history in the session variable unless I'm clicking on the "Back to Previous Page" link since that link will have the "rem" code. I'm also a bit suspicious of the $_SESSION['current'] = $_SERVER['REQUEST_URI']; and where it should be placed.

You can store array in a session and treat the array like a stack (use array_push and array_pop accordingly). When the user hits something but the back button, push the current page to the stack. otherwise, pop it.

I would do it like this if I had to:
$_SESSION["history"] = array();
And within the header of every "rememberable" page:
if(in_array($this_page, $_SESSION["history"])) {
unset($_SESSION["history"][array_search($this_page, $_SESSION["history"])]);
}
array_push($_SESSION["history"], $this_page);
What this does is: "If the page exists in the history, remove it from wherever it is and put it as the last page of the history. If not, just put it as the last page of the history". That way you won't have any loops.

Related

Wordpress: check if last visited page was homepage?

I'm fairly new to Wordpress, and really need some help on the PHP bit. On my wordpress pages (Let's call it Page A), I want to call a jQuery animation, but only if the visitor clicked a from my wordpress home page to get to Page A.
So just to be clear, how can I call a jQuery animation on page A given that the previous page was the homepage?
I wanted to use is_home() to test the page the visitor came from. But as far as I understand, is_home() can only be used to test if the current page is the homepage.
Is there a way to get around this?
You can use History object it has back method and you can check if it returns URL of your homepage
The other option is to use cookies on all your pages
$.cookie("previousPage", window.location.href, {path:"/"});
and then check on PageA
if($.cookie("previousPage") == 'yourhomepage') {
//call animation
}
notice:
$.cookie is available if you use jquery cookie plugin which can be found here
useful links:
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
https://developer.mozilla.org/pl/docs/Web/API/Document/referrer
https://github.com/carhartl/jquery-cookie
The WordPress PHP function get_home_url() gives you the URL of your home page (see documentation). Then in the JavaScript you can use document.referrer to compare with:
var home_page = '<?php echo get_home_url(); ?>';
if(home_page == document.referrer) {
//Animate with jQuery, or whatever it is you want to do.
}
You can also get the previous page in PHP using $_SERVER['HTTP_REFERER']. Wheter you use JavaScript or PHP the information might not be reliable since it comes from the browser. But if it ain't important that it's right every single time it is good enough.
Please note that this won't work if you for some reason have single quotes (') in your homepage URL.

Refresh only a div ("content") by universal button working on every page

To be clear - Ive already checked other Questions about refreshing div and the ideas I found were not exactly what I look for.
My site is made of plenty pages with the same header and footer (top, bottom, menu on both sides). I use smarty templates, and the Whole action of every page happens in one <div id="content">.
My users use to refresh most of those pages many times to do an action they've already done once again. With refreshing browser loads again header, footer, viewed page etc. I would like to bring them the button (instead of F5) which will refresh just a current content page (e.g. account.php) without refreshing whole site.
One of plenty structure:
<?php
$title = 'OneOfPlenty';
require_once("includes/head.php");
{
Whole action
}
require_once("includes/foot.php");
?>
header.tpl ends with <div id="content"> then comes
onofplenty.tpl and then in
footer.tpl I got </div> (close the content)
Here comes the question: Is it even possible? Am I able to create such a flexible button which will recognize which page is being displayed and will "know" to refresh just the content of this page?
Any ideas and help will be aprreciated.
Thank you
TTed
You could do an Ajax call with jQuery to get the output html of the tpl file of the page.
You could use an Ajax call, e.g. by using the jQuery get() function, e.g. like this
$.get("includes/account.php", function(data) {
$("#content").html(data);
alert("Load was performed.");
});
If you saved some kind of variable, either to session or to a data-content on your div. Just so you know which page you are on. Say if you are on account.php you set $('#content').attr("data-content", "account"). Then if you press the refresh button you could use an ajax get on $('#content').attr("data-content") + 'php' to re-import the data. Could be done with a SESSION variable as well.

Display "Please Wait" between form submission and redirect

I have a page that contains an HTML form that submits back to itself once the user clicks a link in a list of returned search results. Once they click the link, the page takes the submitted variables, runs a bunch of searches on various external APIs, parses a bunch of data, and adds a bunch of stuff to the database, then redirects to a new page that has been created from that data.
All the searching and parsing can take up to six or seven seconds; I'd like to be able to show the user a "Please Wait" kind of message while all that work is happening behind the scenes.
Trouble is, I can't show and hide a DIV because it will screw up my PHP redirect if I've already generated output before the
header('Location: ' . $newURL);
command. I've searched around for answers but while there are many that are similar, none of them are close enough to my specific situation that I can hack around them.
I'd be grateful if someone could point me in the right direction.
Updated version which now works, courtesy #Izkata from his comments below:
jQuery("a").bind('click', function() {
jQuery('#feedback')[0].innerHTML = 'Searching, please wait...';
})
Turned out what I needed to do was assign bind a the message to the click of a link, not to 'submit', as submit was looking for form data.
The simplest way I can think of doesn't require the server to do anything:
<div id='wait_message' style='display: none;'>
Please wait while search is in progress...
</div>
...
$$('.links').observe('click', function(e) {
$('wait_message').show();
});
(Event is written using Prototype.js; you should use whatever is appropriate (JQuery/mootools/etc))
Using the example page in the comments, this works - it runs in Firebug, so just putting it on your page somewhere should work just fine.:
jQuery('#newMovieSearchForm').bind('submit', function() {
jQuery('#feedback')[0].innerHTML = 'Searching, please wait...';
})
There's probably a jQuery-way to update the text instead of using innerHTML, but I don't know it - we don't use jQuery here.
You are right, you won't be able to output data to the screen and then try to redirect afterwards using PHP. You could accomplish this by echoing JS:
echo 'Please wait...';
// Time-intensive PHP here
echo '<script>window.location = "new-location.php";</script>';
You can do something like this:
First, take care of output buffering, i.e. you want php to display output as it executes - you don't want it to buffer.
That way, you can output some html that will show a "loading.." sort of thing.
And, will wait for the script to end it's execution.
Once, you are done with php, redirect using a meta tag, something like:
echo '<meta http-equiv="refresh" content="5;URL=\'http://example.com/\'">';

help with javascript confirmation dialog

So here's my situation: I have a form that validates with PHP. I want to make it so that if the form fails validation, the user is forced to click through a confirmation dialog before they navigate to another page (the form is fairly large and they don't want to accidentally leave it before it's saved). I'm going about this like so:
see updated function below,
Basically use php within the function to either set the body to present the confirmation or do nothing depending on the error status of my form. Nothing happens when the form isn't submitted and I click a link, good. When the form is displaying errors and I click a link the confirmation dialog will appear but canceling it causes it to reappear. If I cancel it a second time the page request will go through even though it's not supposed to. I'm not that familiar with javascript so I'm not sure what's going on. Is there a better way I should be going about this?
Edit: I figured it out, it was a combination of things. The first was a really dumb mistake on my part: I was calling the onlick on both tags AND the tags for each link in my list, hence why the box popped up twice.
the second piece was that even though my function already returns bool, the onclick requires an explicit return declaration. I was doing:
<a onclick="forceConfirm();" href="somepage.html">Blah</a>
When it should have been:
<a onclick="return forceConfirm();" href="somepage.html">Blah</a>
Then just edit the PHP so that forceConfirm always returns true when the form hasn't been submitted, bypassing the confirmation:
function forceConfirm(){
<?php
if($form->errorStatus){
echo 'if(confirm("Are you sure you want to navigate away from this page? All unsaved changes will be lost.")){'."\n".
'return true;'."\n".'}'."\n".
'else{ return false;}';
}
else{ echo 'return true;';}
?>
}
Now I just need to figure out how to use jQuery to apply this to all links without having to put onclick events all over the place....
You can use confirm() like this:
if(confirm("Are you sure you want to proceed?")){
document.location = 'confirmed redirect url...';
}
else{
document.location = 'cancel redirect url...';
}
Then you'd wrap that in the same PHP block as in your example, displaying it if necessary and hiding it if not.

Keep a div from reloading

Basically, I want the same effect as the oldschool html 'frameset' I think.
Take a look at this page please:
http://onomadesign.com/wordpress/identity-design/alteon-a-boeing-company/
If a user selects a project from industry -> transportation for example, I would like that the right scrollmenu keeps its initial state when the new project page comes up. So they won't get lost and have to click again to be in the same submenu section.
So, the right thumbnail navigation should stay in the same way, I don't want it to reload.
Do I have to do it with frames or iframes? Or can I make some kind of jQuery call to 'not reload' that div? Maybe PHP? I'm sorry, I am not a programmer from origin.
Update:
Guys, I managed to put the whole thumbnail navigation code into a seperate php file, called sidebar.php. Now this gets called in my single.php (Wordpress) by <?php get_sidebar(); ?>.
Should it now be easier to make this sidebar.php NOT refresh on page reload? I've been looking at cookies, php sessions, iframes.. but I can't get it to work.
Any more help would be greatly appreciated!
Facebook kinda does this without frames for optimization's sake. They take every single link and, if supported, using AJAX to load the page content without reloading the layout.
Obviously, this sort of thing may require significant restructuring of the internals of your app. Another option is to simply store the menu's state as a cookie on link click (see the jQuery Cookie plugin) and, on every reload, either have Javascript look at the cookie and dynamically restore the menu to its correct state, or use your internal PHP to read the cookie and decide what menu to display.
But if you get really desperate, you may end up falling back on frames. Sometimes that can be okay - but try everything else first :)
You also can detect what menu item was activated (you got the page request due to clicking on the corresponding link) and use this information to restore/select this menu item.
At least that is what I do and... No cookies or AJAX required!
You can use a technique known as "AHAH" Asynchronous HTML and HTTP. Essentially you're doing a jQuery
$.post("whatever.html",function(data) {
$("contentdivelement").html(data);
}
You can wrap this in a function like:
updateContent(sPage) {
$.post(sPage,function(data) {
$("contentdivelement").html(data);
}
}
This will load the content from your "frame" page into the div without reloading the page.
You can also bind to each of the navigation links and use their HREF as your path to load in your content div such as:
$(".menuLink").click(function() {
var menuLink = $(this).attr('href');
updateContent(menuLink);
/* prevents the browser from taking the parent to that link */
return false;
});
ADDITION:
Your menu may look like this:
<ul class="myMenu">
<li>Frame 1</li>
<li>Frame 2</li>
</ul>
Also,
If you want it to remember the page you're on you can use cookies or #anchors. There are many ways to add "tab" or "menu" anchors but one way would just be to use a jQuery plugin.
The most COMMON and TRENDY way to do it is to use #anchors. Your browser address bar ass #frame1 to the end so when the page is refreshed or reloaded it will load up "frame1" automatically with some additional code.
You can even called the anchor #/frame1.html and read the anchor in
$(document).ready(function() {
/* you'll need to either use a plugin or parse out the anchor from your current browser address bar */
updateContent(anchorContentVar);
});
Instead of updating your content using click-handlers I suggest a slightly different approach. Just replace your hyperlinks with this kind of link:
#info_page
Now set up a simple interval that reads out the current URL and updates the DIV accordingly:
__LOC = document.location.href;
setInterval(function(){
if (__LOC!=document.location.href) __LOC=document.location.href;
var fetchURL = __LOC.split("#")[1];
$.get( "/getcontent/"+fetchURL, function(d){ $("#mydiv").html( d ); } )
} 1000);
This allows visitors to use bookmarks as well.

Categories