How to store the state of a page between reloads? - php

I have a website that loads its content by the user clicking a button, then the clicks calls a javascript function that updates just the content of a central <div> element by changing its inner html with AJAX and jQuery.
So for example, when the visitor wants to go to my contact page, they click the contact button, and the div's content is updated to the contact form by pulling that content from an external file and using it to replace the div's innerHTML. The actual address of the entire page doesnt change, as the entire page isnt being reloaded, just the innerHTML of the div.
Further to this, my site uses PHP, and I've coded it such that various content can be populated in the div on page load by passing variables in the url. For example, index.php?page=home will tell the PHP script to load the home page content from an external file, while index.php?page=contact will load the contact form. This way search engines can find each page and their content by following these links in my sitemap.
My problem is that if a visitor clicks a button and loads different content into the div, then clicks the reload button of their browser or presses CTRL+R, the entire page reloads and the div of course reverts to its original content.
My question is, is there a way to load a particular page when the browser refreshes? For example, if the visitor has loaded the page index.php?page=home then clicked on the contact button and updated the div content, then pressed the refresh button of their browser, can i somehow write a script that will load index.php?page=contact instead, preserving the look of the page and the content?

Option 1: location.hash
Easier, but not as robust. Worth taking a look at, but if you want to store the states of multiple elements, you probably want option 2.
Here's a demonstration of the code below.
Example:
function onHashChange() {
var hash = window.location.hash;
// Load the appropriate content based on the hash.
}
$(window).on('hashchange', onHashChange);
$(document).on('load', onHashChange);
$('#button').click(function(){
window.location.hash = "home";
});
This way, all you need to do is change the hash on button change and handle the page load using the hashchange event.
Option 2: History API using History.js
A little harder to implement (but not much!), but infinitely more robust. Relies on a widely used framework.
Another, and perhaps a cleaner way of doing this would be to use the History API. It allows you to change window.location without refreshing the page, allowing you to handle those changes using JavaScript.
Not all browsers support the API yet though, but you could use History.js, which provides location.hash fallbacks if needed. Here's a demo.
From History.js's github page:
History.js gracefully supports the HTML5 History/State APIs
(pushState, replaceState, onPopState) in all browsers. Including
continued support for data, titles, replaceState. Supports jQuery,
MooTools and Prototype. For HTML5 browsers this means that you can
modify the URL directly, without needing to use hashes anymore. For
HTML4 browsers it will revert back to using the old onhashchange
functionality.
Example of History.js:
function onStateChange() {
var state = window.History.getState();
// Handle state accordingly.
// Fetch the data passed with pushState.
var data = state.data;
var title = state.title;
var url = state.url;
}
// Check the initial state.
$('document').on('load', onStateChange);
// Listen for state changes.
window.History.Adapter.bind(window, 'statechange', onStateChange);
// Any data you want to be passed with the state change.
var stateObj = { variable : 'value' }
// Change state using pushState()
window.History.pushState(stateObj, "State name", "/page.html");
The state name is ignored by most browsers. The third parameter is the bit that gets added to the URL.

Weeks ago I've released a jQuery plugin for this situations, when the developer wants to add ajax content to a page, and dynamically change the URL.
The plugin is jQuery Dynamic URL https://github.com/promatik/jQuery-Dynamic-URL
There is a demo here: http://promatik.pt/github/dynamic-url/
When you load ajax content, you can push a path to the URL, ex:
$.pushPath( 0 /*level*/, "contact" )
Your site instantly turns to: example.com/contact
Or in your case, you can use:
$.pushVar( "page", "contact" )
Your site instantly turns to: example.com/?page=contact
This plugin also allows you to do this:
Imagine that you give me a link for: example.com/?page=contact
In the index page, $.getVars( ) will return: {"page" : "contact"}
So with this info you can build your page based on the this queries.
There's more thigs you can do with the plugin, like listening to event onPopState (that means user went back or forward in browser, so you can rebuild your pages based on that) just try out the demo...
Important information: This plugin works in all modern browsers except IE9, witch works partially, you still can access url data like example.com/?page=contact (and build your page based on this queries) but not modify dynamically the URL during the user experience.

Related

hide url in navigation bar

I have different pages and scripts on my website. I want to show 1 URL in the adressbar for all the pages.
I have pages like:
www.example.com/index.php
www.example.com/map1/index.php
www.example.com/map1/map2/index.php
www.example.com/map1/map2/map3/index.php
I want that all these URLS should be shown like:
www.example.com
I have expirimented with my .htaccess script, but I cant get this working.
Can anybody help me with this problem? How can I show all the URL`s on my page like "www.example.com".
You could make www.example.com/index.php (which would be the default for www.example.com) be the only page that actually gets loaded fully, with all the others simply providing content to be loaded via ajax.
You could also make www.example.com/index.php contain only an iFrame or a frameset, such that clicks to other locations would only be to the nested frame, leaving the address bar always at www.example.com
You could also try taking "map1" and "map2" etc out of the URL and use them instead as post variables, or $_SESSION variables, or what have you.
Hide the Target URL of a Link in Status Bar
There are some instances where you have redirect the user through one page to get them to another page. There is a way to do this stealthily - without letting the user know that there was a redirect. Yes - it sounds evil - but it don't have to be. Say you have a click tracking software - you have to track each click the users make. To do that you need a redirecting page what will track the clicks. Hopefully, the following illustration will make things clearer...
Current Page->Page with the click counter->Destination Page
You don't want the user to see that you are passing through the middle page. Usually, the URL will flash in the address bar for just a second(or less) - so we don't have to worry about that. We just have to prevent the URL from appearing in the status bar when the user hovers over the link.
There are three methods to do this...
Change the status text
Hijack and stop the click event and redirect
page.
Make an Ajax call on click event.
Changing Status Text
This is the old method. This uses the window.status property to show a different URL to the user. Simple and easy method - but it rarely works now a days. This method has been abused by malicious sites a lot - so most browsers have disable this option. In Firefox, you can find that option at Tools -> Preferences -> Content -> Enable Javascript(click on the 'Advanced' Button) -> Change status bar text. If that's checked, you can use window.status to change the status bar text. But its disabled by default.
But if you still want to use this method(not recommended), this is how to do it...
<a href="click_counter.php?redirect_to=http://www.google.com/"
onmouseover="window.status='http://www.google.com/';return true;"
onmouseout="window.status='';">Go To Google</a>
Hijacking Click Event
In this method, when the user clicks on the link, the script captures the click event and stops it. This will prevent the browser from opening up the target page. Then we use location.href to go to the new page. Sample code below...
HTML Code
Go To Google
Javascript Code
<script type="text/javascript">
function init() {
document.getElementById("google-link").onclick=function(e) {
e=e||window.event;
stopEvent(e);
location.href="click_counter.php?redirect_to=http://www.google.com/";
return false;
}
}
window.onload=init;
</script>
Ajax Method
This is for all you web 2.0 fans. Ajax method simply makes a call to the counter server side script on the click event. This is perhaps the best method of all - as the counter URL doesn't appear at all. Needless to say, the server side script used here will be different from the one used in the other methods - there is no redirection here. The code is very simple as well...
HTML Code
Go To Google
**Javascript Code**
<script type="text/javascript">
function init() {
document.getElementById("google-link").onclick=function(e) {
jx("counter.php?url="+escape("http://www.google.com/")); //Use your favorite ajax library here.
}
}
window.onload=init;
</script>

hide tab when no content & load content after onclick tab

I have built a jquery tab that shows or hides the tab button if its content is empty or not.
Now, because of the pageload, I would like to only load the content when someone clicks on the tab button.
This is the code to check if there is content or not, and hide the tab if empty:
$j(function() {
if ($j.trim( $j("#CONTENTDIV").html()) == "") {
$j("li#TABBUTTON").hide();
}
});
How do I make this load the content when clicked, but hide the tab button if it has no content?
If you want to delay loading the contents of the tab until it is clicked, then you cannot know (prior to clicking) whether or not the tab should be shown (has content) or not (has none).
Philosophically, you could create a lightweight, AJAX function that requests an (essentially) empty page that simply asks for whether there is any value in a database field and simply return true if there is any content -- not the whole page. Then, on click, you could retrieve the contents.
Edit: This assumes, of course, that you can detect some value without retrieving the whole page.
Even if the request for the resources has to retrieve the whole amount, I believe the server should be able to access the resources more quickly than it would take to deliver the content to the user -- particularly if the resources reside on the same server that is doing the checking. Regardless, since it is being done in AJAX, you can keep the tabs hidden and show them ($("#myTabID").show())as the lightweight, AJAX function discovers available content.

Image Gallery With New Page per Slide

currently I have the a basic jQuery gallery:
<ul>
<li>IMAGE</li>
<li>IMAGE</li>
</ul>
// with NAV stuff
I cycle through the images with animations and everything works great.
However, my client "NEEDS" another setup, whereby there will be a new page per slide. GQ.com is a good example of this. Click the link to check it out.
If you will notice, each time you click 'Previous' or 'Next' a new page is loaded, creating more pageviews for the site.
My Question:
Is it possible to have this with my current setup (b/c it can't change)? Or is it only possible through the server-side programming? How are they doing this?
Take a look at what's actually happening there. The URL for the "next" button looks like this:
Next
But when you click on it, where does it take you? You get here:
http://www.gq.com/style/wear-it-now/201010/best-jean-jackets-denim#slide=2
Notice the difference? It's a hash # instead of a question mark ?. They aren't reloading the entire page, they are making an HTTP request asynchronously in Javascript and using some form of hijax to change the browser's hash value (that which appears after the #...the only part that javascript can change), thereby allow the user to cycle backward and forward with the regular browser controls. The way to do this is to build in methods in your javascript to detect the value of what's after the hash both on page load and after a page's hash value has changed. Then you can have another javascript function actually control changing it when you click the "next" or "previous" buttons, and return false to kill the normal anchor href execution.
The reason this is called "hijax" is because your site still has perfectly-valid hrefs (e.g. you can go to that link above but replace the # with a ? and get to the exact same application state). This allows search engines to crawl your site and users without javascript to effectively use your site, while also providing all the AJAXery that people expect in fully-featured browsers. The trick here is to make sure that what comes after the # can be passed via AJAX to your server, have the server understand that it's an AJAX call, and process a return value that your javascript can understand. The easiest way is to use the extra bit after the # as the URL of your AJAX request and let the server interpret everything properly.

HTML toggle button for simple site using php possible?

I've got a simple website using plain HTML/CSS to display and PHP/MySQL for data storage.
Now I'd like to add a toggle button similar to facebooks "like" button.
How can I act on the user pressing the button (add database record for this item, change button text) without leaving the page?
I thought this question would have been asked and diskussied to no end, but all solutions I found require some other frameworks than plain PHP as background.
You'll need to do it with javascript. Read up on "AJAX form posting".
A high level view:
user clicks on button
you capture the click via an onclick handler in javascript, and use it to call a javascript function
said function does a remote url request via XmlHttpRequest to a target page
that target page takes in the parameters passed via POST or GET and performs actions with them (eg add database record), and prints out any response required
the javascript function reads the response and acts accordingly (eg change button text)
and all this happens without refreshing the page.
You can do all this with pure low level javascript code, but plenty of libraries already abstract it while solving various issues with browser compatibilities. I'd suggest the jQuery javascript library. It provides an easy way to do exactly what you require, and good documentation.

Ajax back button with dynamic content

I've created a page using JQuery and Ajax that helps a user filter through a series of options and ultimately displays a filtered list of products meeting their specification.
This all works fine.
The problem i'm having is the "Back Button" problem with Ajax, i know how to get around this with anchors on static content (i.e. Filter.php#Step2).
However, the page works by returning a list of product specifications, when a spec link is clicked, Ajax loads the same page again applying the links parameters, this is repeated up to six times, after which, the user is redirected to the filtered product URL.
If the user then clicks "Back", then of course, the filter page reloads from step 1 rather than the last step (step 6).
Does anyone know if this is even possible?
Every time you want to be able to go back to the previous step, change window.location.hash.
Ie.
window.location.hash = 'step1';
This changes the #foo part in the URL. You will also need a timer in JavaScript which checks if the hash was changed, as there is no way to reliably detect hitting the back button. Something along the lines of...
var oldHash = window.location.hash;
setInterval(function(){
if(window.location.hash != oldHash) {
//the hash was changed, do something
}
}, 50);
I hope this helps
I can't say I've implemented this before personally, but I remember the jQuery Tools tab component doing something similar. I'm not sure if it will work for your particular situation, but it may be worth looking at their approach as a starting point.
jQuery Tools AJAX:ed tabs with History support

Categories