Quick introduction to pushState with Ajax

Posted on Saturday October 27, 2012 / by Eric Potvin

As web technologies keep improving, new way to develop solutions for website evolves. One of them is of course Ajax, this very simple technique is used on a lot of websites now. The one I am more interesting now to talk about is pushState.

The pushState function is a simple way to push a fake URL onto the browser's history stack. It requires three (3) parameters:

State object

The state object is a JavaScript object which is associated with the new history entry created by pushState().

Title

Title of the current HTML page. Firefox currently ignores this parameter. Passing the empty string here should be safe against future changes to the method.

URL

The URL you want to load. This URL is pushed in its history automatically.

Source: Mozilla website

That's should be it for the theory, now let's put these words into code.

HTML

In this example I will have a simple HTML file that shows a welcome message.

<!DOCTYPE html>
<html>
<head>
  <title>history.pushState() Example</title>
  <meta charset="utf-8" />
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
  <script type="text/javascript" src="/download/pushstate.js"></script>
</head>
<body>

<h1>pushState + Ajax Example</h1>
<nav>
  <a href="/pushstateajax/">Home</a>
  <a href="/pushstateajax/page/1/">Page 1</a>
  <a href="/pushstateajax/page/2/">Page 2</a>
  <a href="/pushstateajax/page/3/">Page 3</a>
</nav>
<article>
  <h2>Welcome to PSA</h2>
  <p>This demonstrate how the history.pushState + Ajax works!</p>
</article>

</body>
</html>

Javascript

Now, let's have the Javascript code for this page (defined in the /download/pushstate.js).

window.onpopstate = function(event) {
  getContent();
};
function getContent() {
  var u = location.pathname;
  $.ajax({
    data: {href: u},
    success: function(result) {
      $("p").html(result);
    }
  });
}
$(document).ready(function() {
  $.ajaxSetup ({  
    cache: false,
    url: "/path/to/script.php"
  }); 
  $('nav a').click(function(e) {
    var href = $(this).attr("href");
    document.title = 'blah';
    history.pushState('', '', href);
    getContent();
    e.preventDefault();
  });
});

The window.onpopstate is used when the use navigates on the website using the back and the foward button. You want to make sure the previous or current content loads properly.

Now simply add your logic in your PHP script. In this case, you will use the $_GET['href'] to process or validate which page to load. Of course in this example I am using the SEO clean URLs and if you are using the same logic, make sure your configure properly your .htaccess file or your Apache config.

IE Issue (yes of course)

IE 9 and 10 (until preview 2) are not supporting the pushState() feature. The https://github.com/balupton/history.js from GitHub might be the solution.