rss feed Twitter Page Facebook Page Github Page Stack Over Flow Page

Quick introduction to pushState with Ajax

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 of the current HTML page. Firefox currently ignores this parameter. Passing the empty string here should be safe against future changes to the method.


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.


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

<!DOCTYPE html>
  <title>history.pushState() Example</title>
  <meta charset="utf-8" />
  <script type="text/javascript" src=""></script>
  <script type="text/javascript" src="/download/pushstate.js"></script>

<h1>pushState + Ajax Example</h1>
  <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>
  <h2>Welcome to PSA</h2>
  <p>This demonstrate how the history.pushState + Ajax works!</p>



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

window.onpopstate = function(event) {
function getContent() {
  var u = location.pathname;
    data: {href: u},
    success: function(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);

The window.onpopstate is used when the use navigates on the website using the back and the forward 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 from GitHub might be the solution.