Friday, June 8, 2012

How to show Ajax requests in URL?

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:


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 , this is exactly what I want, however the first format is good too but this is much more beautiful.



  • 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:


Some Tutorials:

Please help me! I've never found any solution to do this, but I don't want to use jquery or any API, or any library, I want to have a working Javascript/AJAX and PHP script.

Source: Tips4all


  1. For the demo linked in your question, achieving that functionality is actually really simple - as it doesn't use any AJAX at all (when you start to add AJAX to the mix, it get's more difficult - explained later). To achieve that functionality you would; upgrade your links to use hashes, then bind into the hashchange event. Unfortunately the hashchange event is not cross-browser compatible, though luckily there are many "history/remote plugins" available - our preferred one over the years has proven to be jQuery History, it's open-source, got great support and is actively developed :-).

    Although, when it comes to adding AJAX functionality to the mix like such sites as Facebook, WBHomes and then you will start to face a whole series of seriously difficult problems! (I know as I was the lead architect for the last two sites!). Some of these problems are:

    How to gracefully and easily upgrade certain internal links to use the History and AJAX functionality, and detect when the hash has changed? while keeping other links working just like before.
    How to redirect from "" to ""? and still keep the experience smooth for the user such that the 3 necessary redirects are as smooth as possible.
    How to submit form values and data using AJAX and update the hash? and vice versa if they don't support Javascript.
    How to detect which particular area of the page the AJAX request is wanting? Such that subpages are displayed with the correct page.
    How to change the page title when the AJAX state changes? and other non-page content.
    How to perform nice intro/outro effects while the AJAX state loads and changes? such that the user isn't left in the dark.
    How to update the sidebar login info when we login via AJAX? As obviously we don't want that login button up the top left to be there anymore.
    How to still support the website for users that do not have JS enabled? Such that it gracefully degrades and still is indexable by Search Engines.

    The only open-source and reliable project I know of which tries to solve all those extremely difficult problems mentioned has proven to be jQuery Ajaxy. It's effectively an extension to the jQuery History project mentioned before, providing a nice elegant high level interface to add AJAX functionality to the mix to take care of those difficult problems behind the scenes so we don't have to worry about them. It's also the chosen solution used in the last few commercial sites mentioned earlier.

    Good luck, and if you have any further questions then just post a comment on this answer and I'll get to it asap :-)

    Update: There is now the HTML5 History API (pushState, popState) which deprecates the HTML4 hashchange functionality. History.js is now the sucessor to jQuery History and provides cross-browser compatibility for the HTML5 History API and an optional hashchange fallback for HTML4 browsers. jQuery Ajaxy will be upgraded for History.js

  2. I think you can do that very easily using the onHashChange event present in HTML5 or using a JavaScript library that emulates that "hash" behavior in browsers that doesn't have full HTML 5 support.
    One such library might be MooTools onhashchange, but there are many others too.

    Than if you have a HTML 5 aware browser, or such library that emulates the behavior just use: window.sethash("#newsection"); to change to something new from javascript, and/or a callback to that onHashChange event to intercept it, depending on your use case scenarios.

  3. CorMVC Jquery Framework is done in that way, it is opensource you can dig into source and get the logic from it.

    And actually it is pretty straight forward. The creator tells it nicely on this video below.

    PS sorry can't post second link bc i'm a new user.

  4. Szevasz.. :)


    <a href="/bye.php?user=abc&page=messages"
    onclick="return goToWithAjax(this);">bye</a>


    function goToWithAjax(hash) {
    hash = hash.href ? hash.getAttribute("href", 2) : hash;
    ajax( hash, function( response ) {
    document.getElementById("content").innerHTML = response;
    hash = ("#!/" + hash).replace("//","/");
    window.location.hash = hash;
    return false;


    function getXmlHttpObject() {
    var xmlHttp;
    try {
    xmlHttp = new XMLHttpRequest();
    } catch (e) {
    try {
    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    return xmlHttp;

    function ajax(url, onSuccess, onError) {
    var xmlHttp = getXmlHttpObject();
    xmlHttp.onreadystatechange = function () {
    if (this.readyState == 4) {
    // onError
    if (this.status != 200) {
    if (typeof onError == 'function') {
    // onSuccess
    else if (typeof onSuccess == 'function') {
    };"GET", url, true);
    return xmlHttp;

  5. 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

    next you will need the jQuery hash change even plugin by Ben Alman which you can find here: 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.

    $(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 so you just call the windows trigger function when the page loads

    $(window).trigger( 'hashchange' );

    Hopefully this is clear enough, if not, don't hesitate to contact me to ask more questions.

  6. Using hash links allows for bookmarkable/sharable links to trigger JavaScript code, instead of reloading the page. Ben Almans jQuery hashchange event allows you to bind an event handler to the hashchange event, this plugin works with older browsers that don't support this normally. An event handler bound to hashchange can read the hash part of the url, and call any function.

    // register event handler
    function bindHashchange() {

    $(window).bind('hashchange', function(event) {
    var label = location.hash.substring(1);

    // trigger event so handler will be run when page is opened first time
    // otherwise handler will only run when clicking on hash links

    // read and handle hash part of url
    function handleLabel(label) {

    if ( label.length > 0 ) {
    // using label from url
    } else {
    // use the default label, if no hash link was present

    // in this case, load hidden <div>'s into a <div id="content">
    function switchPage(label) {
    if ( label == 'start ) {
    } else if ( label == 'some_other_page' ) {
    // do something else

    This other event handler can process 2 arguments separated by a dot ('.') in the same url.

    function processHash() {

    var str = location.hash.substring(1);
    var pos = $.inArray('.', str);

    var label = '';
    var arg = '';

    if ( pos > -1 ) {
    label = str.substring(0, pos);
    } else {
    label = str.substring(0);

    if ( pos > 1 ) {
    arg = str.substring(pos+1);

    if ( label.length == 0 ) {
    // the default page to open of label is empty
    } else {
    // load page, and pass an argument
    loadContent(label, arg);

    If regular expressions are used, any combination of characters can be parsed.

    var registry = {};

    // split on character '.'
    var args = label.split(/\./g);

    for ( i in args ) {
    var arg = args[i];

    // split on character '='
    var temp = arg.split('=');
    var name = temp[0];
    var value = temp[1];

    // store argument in registry
    registry[name] = value;
    // registry is loaded, ready to run application that depends on arguments

    This will transform the url:


    Into the following JavaScript Object:

    Object { company=undefined, page="items", color="red"}

    Then it is only a matter of running jQuery's show() or hide() functions on your selected elements.

    This could be transformed into non-jQuery JavaScript, but then you would lose the functionality that Ben Alman delivers, which is crucial for a portable solution.

  7. What you want is a way to support history in AJAX which can be done using many already existing libraries. I would recommend reading YUI 3 page on history.