Tip: Making the “back” button work with AJAX

About a month ago, I received an email from an otherwise happy user of COMPARTMENTS, who wished there was a way to return to the search results after having clicked a protein. I was just about the send her an email explaining how the lack of “back” button functionality was an inherent drawback of using AJAX, when I thought that it would be wise to do a quick Google search first.

The result was a healthy serving of humble pie from Stack Overflow. It turns out that you can make it work fairly easily by using the history.pushState() method to manipulate the browser history. Because my search page already allowed the query to be specified as a URL parameter, one extra line of JavaScript code for the “Search” button was all it took to fix the “back” button behavior.

So there you have it. AJAX is no excuse for the “back” button not working as it should.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s