Browser navigation with AJAX pages

Recently I came to this issue, and after a lot of googling around I found a simple and powerful solution so I thought it would be beneficial for everyone to know about it. It’s called jQuery Address, and you can find it on the page of Asual. Let’s download it now.

My main problem was that I’m hijaxing almost all of my links in my ASP.NET MVC application, and doing this prevented me from using the browser’s back and forth buttons. I could easily live with this, but my designer couldn’t so I had to come up with a solution. I must warn everyone that it was just pushed together in a hassle, and you could almost see the duct tape holding it together, but it works (for now).

So get the jQuery address plugin, and include it in your project. Then just call the $.address method of it on the anchor tags you wish to hijack – my example:

$(".ajaxLink").address();

This initializes the logic, and you can see a nice #/pageURL appended to your query string. You can now go back and forth in your browser, even bookmark your pages, but doing so won’t result in any change, just the URL will change in the browser’s nav bar. But we needed just that!

 Now my idea was that I would do this dead simple (and a bit simplistic). So I needed the URL’s part after the double-cross symbol, and then feed it with my browser. Fortunately, there’s an event for browser-originating events that result in URL changes in the Address plugin, which is called externalChange. I’ve come up with this solution:

$.address.externalChange(function(){
    var address = document.location.toString();
    var newUri = address.split('#');
    $.ajax(
    {type:"GET",
    url:newUri[1],
    cache:false,
    success:function(html){
                           //Now you have your result here, do something with it!
    }
    })});

I warned you that it is simplistic! Just split the uri with the Javascript split method, which returns an array, take the second element of that array and call a jQuery AJAX method on it. Make sure to turn caching off, and voilà! You have a navigable AJAX application. Of course there’s need to check whether newUri[1] exists at all, and the rest, but I told you that this is just a quick fix.

Advertisements

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: