Alex Rivera | Logout

How to show Ajax requests in URL?

Asked 2010-07-08T16:34:00.260
31

What I want is to have links which change a part of the page , and a dynamic URL for it, where I can specify variables such like #calendar=10_2010tabview=tab2

Check this for an exact example: CLICK HERE FOR EXACT DEMO

So here is the link format what I need:

#calendar=10_2010&tabview=tab2

I need to have variables in the links like calendar and tabview so I can change multiple things on a single page without realoading.


Or another format such like on http://www.wbhomes.com.au , this is exactly what I want, however the first format is good too but this is much more beautiful.

  • http://wbhomes.com.au/#/propertiesforsale/houseandland/quinnsbeach-waterland1

Requirements

  • Needs to be accessed from anywhere from example a mail, or if I just write in the url bar.

  • The link should be in the history, so if If I push the back or forward button the page needs to be accessed.

  • Page refresh needs to work too.


Some recources:

Examples:

Edit
Report

1 Answer

0

This is something that eludes most new AJAXian developers. It is though a rather simple issue to solve.

first thing you will need is the the jQuery core which is free at jquery.com

next you will need the jQuery hash change even plugin by Ben Alman which you can find here: http://benalman.com/projects/jquery-hashchange-plugin/ You won't need this for newer versions of browsers that support the html5 hashchange event but you will for older versions of browsers. you don't have to do anything but include this script in your page, it handles the rest.

now for your links you will need to construct them in a query string fashion like so:

<a href="user.php?q=/topic/article" class="dynlnk">Link Text/Image</a>

now you have links that go to pages and can be handled in php in case javascript is turned off. all you have to do is use the super global $_GET and parse the query string to handle page content.

now in your javascript on the page you will need make your links trigger hashchange. You can do that by replacing the ?q= with a # like this.

$(".dynlnk").each(function(){
    $(this).attr("href", $(this).attr("href").replace("?q=", "#"));
});

now your links will trigger the hashchange, the only thing left to do is bind the hashchange to a function that does something. This can be done very simply with jQuery like this:

$(window).bind( 'hashchange', function(e){

    //this splits the part after the hash so you can handle the parts individually.
    //to handle them as one just use location.hash
    pageparts = location.hash.split("/");

});

Now just add what ever code you do to handle your ajax and content.

now you just need one last bit of javascript to trigger the hashchange in case the page was loaded with a hash to begin with

answered 2010-07-20T15:46:51.550

Your Answer