Shaun Mccran

My digital playground

20
O
C
T
2011

Using URL hashes to control AJAX requests

Following on from my previous article here (http://www.mccran.co.uk/index.cfm/2011/10/17/Adding-hash-values-into-URLs--The-basics) this article deals with injecting Hash values into URL's and using them to power AJAX requests.

Starting with the code of the previous article I'll expand it to include an AJAX request based on the Hash inserted into the URL.

As in the code used previously I'll start off with a list of items. Each of these items is attached to a JQuery selector but also still has a normal hyperlink. This ensures that the link will still work if the user is not using JavaScript.

view plain print about
1<ul>
2    <li><a href="home.cfm" class="ajax-link" id="home">Home</a></li>
3    <li><a href="about.cfm" class="ajax-link" id="about">About</a></li>
4    <li><a href="buy.cfm" class="ajax-link" id="buy">Buy</a></li>
5    <li><a href="contact.cfm" class="ajax-link" id="contact">Contact</a></li>
6</ul>

Next create a JQuery selector that is watching for click events on anything with a class of 'ajax-link'. The function below will pull out the id attribute of the clicked object, then push that value into the URL as a hash value.

Next we stop the default behaviour of the hyperlink (IE stop it moving the user to the page) and perform some simple manipulation. All I'm doing here is adding a 'cfm' string to the end of the value.

Lastly push this value into a standard AJAX request, this will basically fetch the page and handle the response by injecting the returned page content into the designated div element.

view plain print about
1<s/cript language="javascript">
2    $(document).ready(function() {
3
4        // click event listener
5        $('.ajax-link').click(function(event) {
6
7            // get the id
8            var clickedLink = $(this).attr('id');
9
10            // push it into the url
11            location.hash = clickedLink;
12
13            // debugging alert
14            //alert(clickedLink);
15
16            // stop the regular href
17            event.preventDefault();
18
19            var remoteurl = clickedLink + '.cfm';
20
21            $.ajax({
22                url: remoteurl,
23                success: function(data, textStatus){
24                    $('#injected-content').html(data);
25                }
26            });
27
28        });
29
30    });
31</script>
32<div id="injected-content" class="injected-content-holder"></div>

There is an example of this working here: http://www. mccran/examples/jquery-url-hashes-ajax-request/

Related Blog Entries

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Adam's Gravatar ummmmm, not to sure why this would be of use?

Is there a specific reason why to add hash to the url?

Also, is there a reason why you append .cfm to the ajax url when you could get the value from the href.
# Posted By Adam | 20/10/2011 14:56
Shaun mccran's Gravatar Hi adam,
Adding hash values to urls can be handy for a number of reasons, you could use them as in this case to denote a string separator, where the right hand side is a variable to be used in other JavaScript functions, this is handy for analytics tracking as well. The other point with them is that they inform the browser not to cause a page load. Ie the user isn't actually pushed to a new url they stay where they are.

I'm appending '.cfm' here just to demonstrate that you can manipulate the value easily. Where I've used this in recent real world projects I've performed much more complicated regex pattern matching here to retrieve content from a more elaborate folder structure.

I'm treating this very much like a client side way of coding SES urls using javascript instead of a server side htaccess file.
# Posted By Shaun mccran | 20/10/2011 15:16
adam's Gravatar Hi - so sorry, but still don't get it. maybe its the example you are giving. I get the .cfm bit.. fair enough, but the hash bit?

If using ajax, the browser wouldn't refresh anyway. As for SES, nope just can't see how this would help if relying on Javascript, since robots don't do ajax.
# Posted By adam | 20/10/2011 16:05
Shaun McCran's Gravatar Ok, look at it this way, I want to use AJAX to bring dynamic content into a site, but I also want my users to be able to get back to that page in the same state that it is, and also be able to use their usual browser controls.

If I don't create a unique URL in some way users cannot bookmark the current state of the page.

You are right about the fact that emulating SES in JavaScript isn't valid for Search engines or Robots.txt files. What it is valid for though is showing users where they are.

The idea here is to build ULR's that actually show users where they are. Doing it this way ensures that there is a clear heirarchy present in the URL and that users can see it.
# Posted By Shaun McCran | 23/10/2011 07:29
adam's Gravatar Shaun - Believe me, I understand and have used this method before, what I was confused about was the blog entry. I think to make things clearer you could have mentioned to your readers that this is good for bookmarking and the like. Although the practical use of this might be in YOUR head it would be better to let the reader know this?
Anyway, that aside, there is a newer method of doing this now (although the hash method acts as a fallback for older browesers) - I suggest you get up to speed with "window.history.pushState".
# Posted By adam | 24/10/2011 05:09
Shaun McCran's Gravatar Hi Adam, thanks for the comments, they are all appreciated.

You are right, I probably could have explained the logic behind the post a little more, I plan on doing that in the next post about this subject, where I ditch this approach altogether and build JavaScript watcher functions to monitor URL changes.

In terms of the newer methods of doing this I've assessed them, there was a fair bit of research into this technology before myself and my team started the project where this is used. Unfortunately there are too many issues about browser compatibility and technology compliance.

Both of these links sum up some of the html 5 issues nicely.

http://www.battlehorse.net/page/2011/02/12/html5hi...

http://www.adequatelygood.com/2010/7/Saner-HTML5-H...
# Posted By Shaun McCran | 24/10/2011 13:00
help me write my essay's Gravatar Which is attractive much an expansion for jQuery History to add Ajax to the blend. As when you establish with Ajax hashes it get relatively difficult!
# Posted By help me write my essay | 10/07/2015 03:13
facebookentrar's Gravatar I understand what you bring it very meaningful and useful, thanks.
http://www.facebookentrardiretoagora.com/facebook-... | http://www.facebookenespanoldescargar.com/facebook...
# Posted By facebookentrar | 07/08/2015 02:33
Francis's Gravatar I have tried many ways to control AJAX requests, but unfortunately I couldn’t do it successfully. After following the procedure that has shared in this blog I am able to do it properly. Thank you very much! http://www.originalorkopina.com
# Posted By Francis | 09/09/2015 21:19
saleonleather's Gravatar When the opening application like online shops be produced, a condition or sitting would contain prove enormously helpful.
# Posted By saleonleather | 29/09/2015 00:31
Anonymous's Gravatar A few individuals considered that it is exceptionally hard to compose viable article which pass on the message as well as let the peruse to welcome your written work aptitudes. We propose that any business http://www.websberry.com/outsource-seo-services do in like manner, and honestly, planned exertion is a segregating bit of your very important orchestrating system.
# Posted By Anonymous | 30/09/2015 04:12
Adamstewart's Gravatar I would similar to to next the advice of mixer. You won't discover a improved, additional complete tool for responsibility 3D for gratis. I'm certain the large profitable letters can do additional but they are very luxurious .http://www.revealcode.com/coupons/livingsocial
# Posted By Adamstewart | 30/09/2015 11:00
cosmetic surgery's Gravatar As in the code used previously I'll start off with a list of items. Each of these items is attached to a JQuery selector but also still has a normal hyperlink. This ensures that the link will still work if the user is not using JavaScript.
# Posted By cosmetic surgery | 03/10/2015 07:02
withdrawal symptoms's Gravatar As in the code used previously I'll start off with a list of items. Each of these items is attached to a JQuery selector but also still has a normal hyperlink. This ensures that the link will still work if the user is not using JavaScript.
# Posted By withdrawal symptoms | 07/10/2015 05:43
fiverr blog commenting's Gravatar this will basically fetch the page and handle the response by injecting the returned page content into the designated div element.
# Posted By fiverr blog commenting | 23/11/2015 02:39
laurensinclair110 wordpress's Gravatar this will basically fetch the page and handle the response by injecting the returned page content into the designated div element.
# Posted By laurensinclair110 wordpress | 04/12/2015 22:07
facebook likes's Gravatar Your website is really cool and this is a great inspiring article. Thank you so much.
# Posted By facebook likes | 14/12/2015 23:45
youtube views's Gravatar Thanks for sharing the info, keep up the good work going.... I really enjoyed exploring your site. good resource...
# Posted By youtube views | 14/12/2015 23:46
dedicated server's Gravatar Your website is really cool and this is a great inspiring article. Thank you so much.
# Posted By dedicated server | 19/12/2015 23:31
cheapwritingservice.org's Gravatar Firstly create a CurrencyFormatter object, and specify the currency symbol, and any other formatting parameters that you require.
# Posted By cheapwritingservice.org | 26/12/2015 02:29
read more's Gravatar Good to become visiting your weblog again, it has been months for me. Nicely this article that i've been waited for so long.
# Posted By read more | 28/12/2015 02:09
garcinia cambogia canada's Gravatar Firstly create a CurrencyFormatter object, and specify the currency symbol, and any other formatting parameters that you require.
# Posted By garcinia cambogia canada | 28/12/2015 05:23
read more's Gravatar Your site and show the kids check out up here generally. I m fairly positive there likely to be informed a great deal of new stuff here than anyone.
# Posted By read more | 29/12/2015 01:56
sell on amazon fees's Gravatar I have feel that this blog is really have all those quality that qualify a blog to be a one.I wanted to leave a little comment to support you and wish you a good continuation.
# Posted By sell on amazon fees | 09/01/2016 02:52
Back to top