Search code examples
javascriptjqueryajaxpathname

jQuery Page Load According to Location Pathname


I'm currently having trouble trying to load a page according to a header through jQuery! Initially when I load a page through .click, I change the header to #/Pathname. Now where my problem comes is, rather than individuals having to constantly go to the main page and then click a button where it leads to that pathname I want them to be able to go directly to www.example.com/main.php#/Pathname and have jQuery be able to load the page... would that be possible? I tried this code, but no luck:

if (document.location.pathname == "main.php#/Home") {
            $('#content').load('home.php', function( response, status, xhr ) {
          if ( status == "error" ) {
            var msg = "Sorry but there was an error: ";
            $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
          }
          });
}

Ignore the error script it's just there for my own purposes!


Solution

  • I assume that you are trying to manage "state" of page.

    I highly recommand you to have a look on window.history.pushState that helps you rewrite properly the URI of your page but also manage proper History sessions.

    To push a state :

    window.history.pushState("","",URI );
    

    to popState

    window.addEventListener('popstate', function(event) {

    your code here to manage event history
    

    });

    Moreover, you are also having trouble PARSING your URI. I use that function for uri parsing and checking as my pages are with parameters such as ?id=...&name=

    function getUrlParameter( name )
    {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return null;
      else
        return results[1];
    }
    

    So in your case, I'd :

    window.history.pushState("","",URI + "?page=home);
    

    and to test if on location I have home : => getUrlParameter("home")

    Is your formating of page with #/ mandatory ? If not, use the kind of code I quote that will enable you to manage proper history, goback and more.

    If yes, we will think about another solution.

    If this not completly answers to your question, then please provide more info an what this is not replying. GoodLuck

    --- EDIT

    function getUrlParameter( name )
    {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\#/]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return null;
      else
        return results[1];
    }