Question

I'm using the datatables JQuery plugin. I use it with AJAX and pagination (server-side). Each row contains a link to a detailed view of that record. When clicking in that link and then on the back button I want to return to the previous page. (Note: datatables own state-saving can't be used).

This could be achieved If you could add a url parameter to the current url before it is put into the history.

Can this be done? pure JS or JQuery does not really matter.

(Note: I'm quite new do this kind of stuff, have read about using the # for this but never done it so if you recommend that please provide an example applicable to my problem)

EDIT:

Very basic Guide for JQuery plugin bbq (http://benalman.com/projects/jquery-bbq-plugin/)

Assuming URL has a hash of #a=2&b=test, you can get the values by:

//true = optional converts 2 to an integer, false to boolean,...
var a = $.bbq.getState('a',true);

You can change/add a value by:

var hash = "a=3&b=hello";
$.bbq.pushState(hash);

pushState fires hashchange Event in case it is bound. To bind the event but following in doucment.ready function:

// called when # part of URL is modified
$(window).bind( 'hashchange', function( event ) {
    var hash = event.fragment; // full hash as string
    var a = event.getState('a', true ); // value for a
    // here do meaningful action like an AJAX request using the hash parameters    
});
Was it helpful?

Solution

Yes, the HTML5 History API allows you to do just that. Check out the Manipulating the Browser History article at MDN.

Here is an example that adds a parameter to the current URL and replaces the current history entry:

 var newURL = location.href + (location.search ? "&" : "?") + "myParameter=myValue";
 history.replaceState({}, '', newURL);

The History API is an HTML5 feature and unfortunately not supported on all browsers. However, there is a polyfill named history.js, which claims to bring support to all browsers.

UPDATE:

Instead of rolling your own AJAX history implementation you would probably want to look at existing solutions and jQuery plugins. Have a look e.g. at the answers to the What is the best back button jQuery plugin? question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top