Following is the code to update content via ajax. Please review all aspects of the code.
var ajaxUpdate = {
init: function(){
ajaxUpdate.enableHistory();
},
_this:null,
enableHistory: function(){
History.Adapter.bind(window,'statechange',function() { // Note: We are using statechange instead of popstate
var State = History.getState();
console.log('History: '+State.url)
if(State.data.type == 'maincontainer'){
if(jQuery('#maincontainer').length){
//update content
jQuery('#maincontainer').html(State.data.response);
//select the menu element
jQuery('#main-menu li').removeClass('active');
jQuery('#main-menu li:eq('+State.data.main+')').addClass('active');
}
else{
window.location.href = State.url;
}
}/*
_this.parent().addClass('active');*/
});
},
updateMainContent: function(){
var _this = ajaxUpdate._this;
if ( !History.enabled ) {
return ;
}
jQuery.ajax({
type: 'GET',
url: _this.attr('href'),
beforeSend : function(jqXHR, settings){
jQuery('#maincontainer').addClass('loading');
},
complete: function(jqXHR, textStatus){
jQuery('#maincontainer').removeClass('loading');
},
success: function(response){
var data = {
main : _this.data('main_index'),
type: "maincontainer",
response: response
}
jQuery('#maincontainer').removeClass('loading');
History.pushState(data, _this.data('title'), this.url);
},
error : function(jqXHR, textStatus, errorThrown){
//processERROR();
}
});
return false;
},
mainmenu: function(){
ajaxUpdate._this = jQuery(this);
ajaxUpdate._this.data('main_index', ajaxUpdate._this.parent().index());
return ajaxUpdate.updateMainContent();
},
submenu: function(){
ajaxUpdate._this = jQuery(this);
ajaxUpdate._this.data('main_index', jQuery('#main-menu li.active').index());
return ajaxUpdate.updateMainContent();
},
search: function(){
ajaxUpdate._this = jQuery(this);
ajaxUpdate._this.data('main_index', jQuery('#main-menu li.active').index());
return ajaxUpdate.updateMainContent();
}
};
ajaxUpdate.init();
jQuery('#main-menu a').click(ajaxUpdate.mainmenu);
jQuery('#maincontainer').on('click', '.nav a', ajaxUpdate.submenu);
jQuery('#maincontainer').on('submit', 'form', ajaxUpdate.search);