Refreshing a URL After An AJAX Call
August 4, 2010 Leave a Comment
This technology post was written by Jorge, one of our engineers in Peru who is also a .NET expert.
A few days ago I was facing a little problem. How can I update the browser’s URL after an Ajax Callback? Well I started doing some research and I found an easy way to solve my little problem. Before pointing you to the solution I want to let you know the context of my situation.
I have a gallery with many thumbnail images. If you click one of them you will be sent to a page where I will show you the original image. The first time everything is OK, because you will see the correct URL. Let’s say I clicked the photo with ID = 1, the URL you will see something like this: http://mydomain.com/Page.aspx?GalleryID=1&PhotoID=1
But what would happen if I click on previous and next buttons? Of course doing an Ajax Callback you will see the right image, but the URL still remains the same. I mean: http://mydomain.com/Page.aspx?GalleryID=1&PhotoID=1 is always shown even if I clicked the next button twice (if I did so, I’m supposed to be at PhotoID=3).
Well the solution I found is to use a nice Jquery plugin jquery haschange event thanks to the contribution of Ben Alman: http://benalman.com. Download the source code and just copy and paste it in your page or in a js file. I recommend you to create a js file. The source code can be found at: http://github.com/cowboy/jquery-hashchange/raw/v1.2/jquery.ba-hashchange.js
Refer your script file at your page, something like this: <script language=”javascript” type=”text/javascript” src=”<%= ResolveUrl(“~/js/jqueryHasChange.js”) %>”></script>
Create a new javascript section:
<script language="javascript" type="text/javascript">
$(function(){
$(window).bind('hashchange', function(){
var hash = location.hash;
var array = hash.substr(1).split('&');
galleryId = array[0].substr(array[0].indexOf('=') + 1);
selectedPhotoId = array[1].substr(array[1].indexOf('=') + 1);
});
$(window).trigger('hashchange');
});
</script>
And that’s it, you’ll see the magic in action. The code I listed here is for the following URL: http://mydomain.com/Page.aspx?#GalleryID=1&PhotoID=1.
Also don’t forget if you have a link for previous to do something like the following, in this case for a Ruby on Rails application: <a id=”navigateRight” href=”#GalleryID=<%= GalleryID %>&PhotoID=<%# GetRightPhotoID() %>”>Next Picture</a>. Notice that for “href” you need to include “#” then the parameter and that’s it.
Enjoy it and happy coding,
Jorge.
