Solving the problem of “back” button in Ajax applications

In: Ajax| Javascript| Jquery| Web Standards| Web developing

9 Mar 2009

Who here has always dreamed in do Ajax applications that the user can freely navigate using the back and forward buttons, and furthermore, can bookmark specific sections? In theory, this isn’t possible, since the “Ajax” is used by most to reload just some page blocks, keeping active the main page and, consequently, precluding the back button or bookmarks use. Otherwise we’d have the good old reload of the entire page.

But then, how the Gmail works? It’s totally in Ajax and yet you can navigate using the back button.  If you put a link like: http://mail.google.com/mail/#compose in the address bar, it will open the e-mail composition screen normally. The big secret is in the #anchors.
Anchor Oriented Navigation

A very interesting thing of the anchors is that they allow you to use the back and forward button, for example, without generate no one full page request and without leaving that page, so, how could we do this?

The first step is create a Javascript file that will be every time verifying if some anchor is active, if so, it sends the Ajax request calling the specific section, based on anchor’s name, that will be loaded inside the main block. Simple, isn’t it?

As is usual for JavaScript today, we will use jQuery, so remember to include the library file in your application.

We would then have a file named “core.js”, thus:

  1. /**
  2. * Loading the page, the timer is started to check if there is an active anchor to each 300ms. */
  3. $().ready(function(){
  4. setInterval("checkAnchor()", 300);
  5. });
  6. var currentAnchor = null;
  7. /**
  8. * Method to check if there is some anchor change, if so, sends the Ajax request.
  9. */
  10. function checkAnchor(){
  11. if(currentAnchor != document.location.hash){
  12. currentAnchor = document.location.hash;
  13. /**
  14. * If doesn’t have no one active anchor, the default section is loaded
  15. */
  16. if(!currentAnchor)
  17. query = "section=home";
  18. else
  19. {
  20. /**
  21. * Creates the result string. Converting the url: URL/#fotos&id=2 in URL/?section=fotos&id=2
  22. * */
  23. var splits = currentAnchor.substring(1).split(‘&’);
  24. var section = splits[0];
  25. delete splits[0];
  26. var params = splits.join(‘&’);
  27. var query = "section=" + section + params;
  28. }
  29. /**
  30. * Sends the request
  31. */
  32. $.get("callbacks.php",query, function(data){
  33. $("#main_block").html(data);
  34. });
  35. }
  36. }

OK, the content will be loaded in th e element of ID “main_block” through the Ajax request result that being sent to the page “callbacks.php” in GET Querystring format.

To catch it, we would have something like this:

  1. $section = addslashes(strip_tags($_GET[’section’]));
  2. $page = "pages/".$section.".php";
  3. if (file_exists($page))  {
  4. include($page);
  5. }

Thus, we would need only a folder called “pages” containing the pages with the anchors’ names.

And to call each section, a simple html page with links like:

http://mysite.com/#photos

It would be detected by the Javascript method “checkAnchor()”, and will be call a php request loading the page named photos.php inside the directory “pages”. It will exhibited inside the block “#main_block” that is contained in the same page of the clicked link, and the best of all, you can back, forward and bookmark the sections you want.

To better illustrate the example, I made a blatant copy (haha) of the PHP-PB’s site, with the only difference of having Ajax navigation through anchors (the original has normal navigation). Access the link: http://www.diegopessoa.com/php-pb-ajax

If you want to download the working example, click here!

6 Responses to Solving the problem of “back” button in Ajax applications

Avatar

ivolnei

January 19th, 2010 at 18:58

Show de bola, estava procurando isso a muito tempo e efim, cá está.
Parabéns.

Uma questão. Se eu quiser mandar um valor pela URL, como faço?

Avatar

Diego Pessoa

January 19th, 2010 at 20:53

Olá Ivolnei, obrigado!

Basta adicionar o parâmetro normalmente após a marcação da âncora, exemplo: site.com/#secao&id=5. O código disponível no post trata também os parâmetros.

=)

Avatar

Candida

April 13th, 2010 at 1:10

Olá Diego… estou fazendo uma página em ajax + php. Esta página pega dados dinamicos e joga em paginações… Só que não estou conseguindo fazer funcionar se a url que envio fica assim: #sistema?idpessoa=1. Tens alguma solução?

Avatar

Candida

April 13th, 2010 at 13:23

Ja consegui descobrir o que era ^^ Mas valeu memso assim =P… super show o tutorial parabens =D

Avatar

Diego Pessoa

May 11th, 2010 at 21:16

Obrigado =)

Avatar

Eduardo

June 24th, 2010 at 20:50

Cara, muito bom. Sabe dizer se o Gmail usa a mesma técnica? Vi que eles usam âncoras e a página não é recarregada ao navegar (modifiquei parte do html com o Firebug e ele não é restaurado).

Comment Form

About this blog

Hi! I'm a Brazilian Software Developer. Degree in Systems for the Internet at IFPB and enthusiast of technologies related to web. Nowadays I'm working as technical leader of the ITVP project at the Dynavideo company. (See more)

  • Eduardo: Cara, muito bom. Sabe dizer se o Gmail usa a mesma técnica? Vi que eles usam âncoras e a página n [...]
  • Diego Pessoa: Obrigado =) [...]
  • Candida: Ja consegui descobrir o que era ^^ Mas valeu memso assim =P... super show o tutorial parabens =D [...]
  • Candida: Olá Diego... estou fazendo uma página em ajax + php. Esta página pega dados dinamicos e joga em p [...]
  • Diego Pessoa: Olá Ivolnei, obrigado! Basta adicionar o parâmetro normalmente após a marcação da âncora, e [...]

Twitter Updates

    Flickr Photostream

    photo photo photo photo photo photo photo photo photo photo photo photo