Saving State in Javascript and AJAX February 25, 2014
We're doing something cool in work, to do with resource scheduling in a nice ajax-y, jQuery-UI-ey way. There are a set number of filters to apply to get the view of the resources you want, which can include Department (for example, Development, Front-End, Client Services, Marketing), the Employee themselves, Employee Roles to show Senior Developers etc, Client and Project. The problem was, these are all filtered via AJAX, and refreshing the page would cause you to lose your filters.
One way that developers solved this was by keeping the state in the "hash" portion of the URL. The most prevalent method of this was called the "Hashbang" which would add the hash (octothorp) and an excalamation point (! - the "bang"). This is easy but could lead to messy / long URL.
Another method that is pretty convenient is to set a cookie containing the parameters. The downside of this is you can't send the same view that you're looking at to a coworker. That cookie is on your computer only.
I couldn't decide which one to implement so I decided to do both.
var serializers = {};
serializers.hash = function(){
this.serialize = function(str){
window.location.hash = str;
}; this.prepDeserialize = function(){
var hash = window.location.hash;
return hash == null || hash.indexOf("#") != 0 ? "" : hash.substring(1);
};
} serializers.cookie = function(){
this.serialize = function(str){
window.Cookie.set("ajaxState_serialize", str);
}; this.prepDeserialize = function(){
return window.Cookie.get("ajaxState_serialize");
};
}
I have a cookie helper class which wraps what you can find on quirksmode.org. If you want to use this code, you can provide your own cookie serializer, your own custom serializers, or whatever, without changing the rest of the code.
The rest of the code is just adding and subtracting values from the serialized data. To call it, it's simply this:
var data = $.fn.projectFilter.getFilterData($wrap);
window.AjaxState.serialize(data, true);
So you get the filter object and serialize it. The true on the call to serialize just says to "commit it", which means to write the data to the cookie or the hash on the same call. I've put this code up on this site, you can download it.