Carlos Miguel Colanta
Carlos Miguel Colanta

Reputation: 2823

Using history.pushstate on jquery ajax

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.

Upvotes: 9

Views: 33858

Answers (1)

Roman
Roman

Reputation: 351

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);
   }); 

});

Upvotes: 13

Related Questions