Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  79] [ 4]  / answers: 1 / hits: 31131  / 8 Years ago, mon, february 1, 2016, 12:00:00

I have a heavily ajax based application wherein i only have a login page and the main page.



Most of my links are ajaxed and i have them done like this:



//get the href of the link that has been clicked, ajaxify ANY links

$(document).on('click', '.tree a', function () {

var link = $(this).attr('href'); //get the href off the list
$.ajax({ //ajax request to post the partial View
url: link,
type: 'POST',
cache: false,
success: function (result) {
$('#target').html(result);
$.validator.unobtrusive.parse($(form#ValidateForm));
}
});
return false; //intercept the link
});


I want to implement pushState on my application and the first step that i have done so far is to add this code:



$(document).on('click', 'a', function () {
history.pushState({}, '', $(this).attr(href));
});


Now it updates my address bar whenever i click on any of my links and the ajax content gets successfully loaded.
I am kinda new to this API so i don't know what am i missing but here are my issues so far:




  1. when i press the back button, nothing happens. I read about popstate and browsed through SO to look for solutions but i can't
    seem to make them work.


  2. When i click the link from the history, i get the raw view of the child html w/o the layout from the master html. What do i need to do if i want it to be displayed like
    it was clicked from my main application?




Most of my child views are either forms or list.


More From » jquery

 Answers
23

This code should help you :



function openURL(href){

var link = href; //$(this).attr('href');
$.ajax({
url: link,
type: 'POST',
cache: false,
success: function (result) {
$('#target').html(result);
$.validator.unobtrusive.parse($(form#ValidateForm));
}
});
window.history.pushState({href: href}, '', href);
}

$(document).ready(function() {

$(document).on('click', 'a', function () {
openURL($(this).attr(href));
return false; //intercept the link
});

window.addEventListener('popstate', function(e){
if(e.state)
openURL(e.state.href);
});

});

[#63481] Friday, January 29, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brendan

Total Points: 426
Total Questions: 110
Total Answers: 94

Location: Western Sahara
Member since Mon, May 3, 2021
3 Years ago
;