Modify Address Bar URL in AJAX App to Match Current State - ajax

I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state.
How are people handling maintaining RESTfulness in AJAX apps?

The way to do this is to manipulate location.hash when AJAX updates result in a state change that you'd like to have a discrete URL. For example, if your page's url is:
http://example.com/
If a client side function executed this code:
// AJAX code to display the "foo" state goes here.
location.hash = 'foo';
Then, the URL displayed in the browser would be updated to:
http://example.com/#foo
This allows users to bookmark the "foo" state of the page, and use the browser history to navigate between states.
With this mechanism in place, you'll then need to parse out the hash portion of the URL on the client side using JavaScript to create and display the appropriate initial state, as fragment identifiers (the part after the #) are not sent to the server.
Ben Alman's hashchange plugin makes the latter a breeze if you're using jQuery.

Look at sites like book.cakephp.org. This site changes the URL without using the hash and use AJAX. I'm not sure how it does it exactly but I've been trying to figure it out. If anyone knows, let me know.
Also github.com when looking at a navigating within a certain project.

It is unlikely the writer wants to reload or redirect his visitor when using Ajax.
But why not use HTML5's pushState/replaceState?
You'll be able to modify the addressbar as much as you like. Get natural looking urls, with AJAX.
Check out the code on my latest project:
http://iesus.se/

This is similar to what Kevin said. You can have your client state as some javascript object, and when you want to save the state, you serialize the object (using JSON and base64 encoding). You can then set the fragment of the href to this string.
var encodedState = base64(json(state));
var newLocation = oldLocationWithoutFragment + "#" + encodedState;
document.location = newLocation; // adds new entry in browser history
document.location.replace(newLocation); // replaces current entry in browser history
The first way will treat the new state as a new location (so the back button will take them to the previous location). The latter does not.

SWFAddress works in Flash & Javascript projects and lets you create bookmarkable URLs (using the hash method mentioned above) as well as giving you back-button support.
http://www.asual.com/swfaddress/

The window.location.hash method is the preferred way of doing things. For an explanation of how to do it,
Ajax Patterns - Unique URLs.
YUI has an implementation of this pattern as a module, which includes IE specific work arounds for getting the back button working along with re-writing the address using the hash. YUI Browser History Manager.
Other frameworks have similar implementations as well. The important point is if you want the history to work along with the re-writing the address, the different browsers need different ways of handling it. (This is detailed in the first link article.)
IE needs an iframe based hack, where Firefox will produce double history using the same method.

If OP or others are still looking for a way to do modify browser history to enable state, using pushState and replaceState, as suggested by IESUS, is the 'right' way to do it now. It's main advantage over location.hash seems to be that it creates actual URLs, not just hashes. If browser history using hashes is saved, and then revisited with JavaScript disabled, the app won't work, since the hashes aren't sent to the server. However, if pushState has been used, the entire route will be sent to the server, which you can then build to respond appropriately to the routes. I saw an example where the same mustache templates were used on both the server and the client side. If the client had JavaScript enabled, he would get snappy responses by avoiding the roundtrip to the server, but the app would work perfectly fine without the JavaScript. Thus, the app can gracefully degrade in the absence of JavaScript.
Also, I believe there is some framework out there, with a name like history.js. For browsers that support HTML5, it uses pushState, but if the browser doesn't support that, it automatically falls back to using hashes.

Check if user is 'in' the page, when you click on the URL bar, JavaScript says you are out of page.
If you change the URL bar and press 'ENTER' with the symbol '#' within it then you go into the page again, without click on the page manually with mouse cursor, then a keyboard event command (document.onkeypress) from JavaScript will be able to check if it's enter and active the JavaScript for redirection.
You can check if user is IN the page with window.onfocus and check if he's out with window.onblur.
Yeah, it's possible.
;)

Related

Ajax generated pages with different URLs

I couldn't really word the title very well, but here's my problem: I've got a webpage that reads from a database each time the user clicks a button, the content is then replaced for part of the page.
Because it is an ajax load, everything is done in the background, and so the URL stays the same. This wasn't be a problem at all until I realised that I will want to have a different Facebook comments box for each set of content that is loaded - so if someone comments, it is posted to their facebook profile, people click on the link and are then taken to different content.
So... what I need is some way of referencing each set of content, and I've found a site that does exactly that (I'm sure there are a lot of them).
Here's the link.
Each set of content has a different 'hash code' (because I don't know the actual name for it) which is appended to the URL - in this case the code is "#1922934", this allows people to post links to it that specific set of content on Facebook etc. - and also allows a different Facebook comment box for each set of content.
Does anyone know how such a set-up can be achieved or how these 'hash codes' work?
Here's a document from wikipedia on it.
[http://en.wikipedia.org/wiki/Fragment_identifier][1]
The main idea is that URI fragments are used because they don't cause a page reload. They also can be used to refer to anchors on a web page.
What I would do is on page load use JavaScript to read the URI fragment (location.hash) then make a request to your server to load the comments etc. The URI fragment cannot be read by a server and is only found through a client (browser)
Sounds like you want something like SammyJS.

Back button to ajax results, advice request

I am trying solve the back button issue within my app. The scenario is:
I have a home page with a search form which sends and receives data with $.ajax(), then the results loaded through ajax, their links points to a controller that won't be done by GET in ajax so that means that the page will be refreshed (so the home page with the results looks like this: http://url/en/home and a result link may look like this http://url/fetch/data/x123av).
The problem is which is the best way fix that when click back button to return the results from the search box?
I have found some answers in stackoverflow related to my question:
http://code.google.com/p/reallysimplehistory
http://tkyk.github.com/jquery-history-plugin
But from the documentation of those plugins, they all work by checking the hash change which I don't have.
Hope I have explained well enough, and I do have searched stackoverflow and google for a solution but I didn't find one that is close to this or either I've jumped over it...
Please just point me to the right way :D
But from the documentation of those plugins, they all work by checking
the hash change which I don't have.
If you want to handle the back button with AJAX request you will have to redesign your application so that it works with hashes as that's the only way. Changing the fragment portion of an url doesn't trigger a page reload but it is added to the history, so when you press the back button you are able to detect this change without navigating away from the page.
As mentioned by SLaks in the comments section another possibility is to use the HTML5 history API but obviously this assumes that the client browser supports it.

ExtJs Back Fwd Buttons

In the past I have developed large extjs single page applications. Many users get frustrated for not being able to use the Back or Fwd buttons or reload the page.I would also like to warn the user if they navigate away from a page without completing a work flow, and enable users to directly access particular views.
For the next application, I am thinking of using the Codeigniter php MVC framework. It is possible to something similar to this example. I am stucked thinking about the navigation. If I load the ExtJs for each view, that is a significant slowdown.
How best to approach this?
Have a look at the Ext.History class (Ext.util.History on Ext4). With it you can register listeners for changes to the hash:
Ext.History.on('change', function( token ) {
console.log('token changed to: ', token);
});
The Ext.History singleton includes forward() and back() methods for triggering navigation from within the client-side code.
By having only the hash part of the URL change the browser stays on the same page, thus eliminating the need to reload the Ext library.
How this would integrate with your PHP framework I cannot say. I am not familiar with CodeIgniter and your example link goes to a dead page.
Also, do note a caveat with History in that under Ext3 at least it may give you issues with newer browsers. If this is the case an alternative is to code your own History-like solution using the 'hashchange' browser event as illustrated in this answer.

Ajax generated content, crawling and black listing

My website uses ajax.
I've got a user list page which list users in an ajax table (with paging and more information stuff...).
The url of this page is :
/user-list
User list is created by ajax. When the user click on one user, he is redirected to a page which url is : /member/memberName
So we can see here that ajax is used to generate content and not to manage navigation (with the # character).
I want to detect bot to index all pages.
So, in ajax I want to display an ajax table with paging and cool ajax effetcs (more info...) and when I detect a bot I want to display all users (without paging) with a link to the member page like this :
JohnBob...
Do you think I can be black listed with this technique ? If you think so, could you please provide an alternative solution by keeping these clean urls and without redeveloping the user-list (without ajax) ?
Google support a specification to make AJAX crawlable:
http://code.google.com/web/ajaxcrawling/docs/specification.html
I did an experiment and it works:
http://seo-website-designer.com/SEO-Ajax-Google-Solution
As this is a Google specification, you won't get penalised (unless you abuse it).
Saying that, only Google support it at the moment (AFAIK).
Also, I believe following the concept of Progressive Enhancement is a better approach. That is, create a working html website then make the JavaScript enhance it
Maybe use the urls with an onclick to trigger your AJAX scripting? Like
Some URL
I don't think Google would punish you for this, you primarily use JScript, but you do provide a fall back for their bot, so your site doesn't get any less accessible.
EDIT
Ok, I misunderstood. Then my guess would be you basically have two options:
1. Write a different part of your site where bots end up, or,
2. Rewrite your current site to for example always give a 'full' page, with an option to only get, say, the content div. Then you can get only the content with JavaScript, but bots will always get a nice page.

What are my options for changing the querystring on a URL, and updating browser history?

Is there any way I can change the URL or add more history to the "back button" without having to refresh the entire page?
My application is AJAX based and I'd like to add some "undo" events to history so that the user can simply hit back and retain the old values.
What's possible today? I hear some of this may be in HTML5 but haven't checked whats supported in current browsers.
I think you can use window.location.hash to track the #part of the page, in your case, #state1, #state2 and so on.
window.location.hash = '#state' + (++ stateN) to set and
stateN = parseInt(window.location.hash.match(/\d+$/)[0])
See On - window.location.hash - Change? for more details about how to detect location hash changes.
You could use 301 redirection. Personally, I would use cookies on the client side, or sessions in your back end, to store the breadcrumbs. Storing state information in the URL is a bad idea for AJAX applications, because people might return to a url that the server side is not in the right state to respond to.
Another option would be to provide your own Back button that knows which page to go back to.
The answer for this question will be more or less the same as my answers for these questions:
How to show Ajax requests in URL?
How does Gmail handle back/forward in rich JavaScript?
In summary, two projects that you'll probably want to look at which explain the whole hashchange process and using it with ajax are:
jQuery History (using hashes to manage your pages state and bind to changes to update your page).
jQuery Ajaxy (ajax extension for jQuery History, to allow for complete ajax websites while being completely unobtrusive and gracefully degradable).
It is possible to use ASP.NET's built in Script Manager to update the browser's history. A full how-to to do this is located here:
http://www.asp.net/aspnet-in-net-35-sp1/videos/introduction-to-aspnet-ajax-history

Resources