Good programming practices

AJAX and normal URL in each link

February 6th, 2011

AJAX allows you to change some part of a page without reloading the whole window. But this raises problems of accessibility for search engines and disabled users. However it is easy to combine both of these methods, offering an AJAX version only there, where it is possible. There is no need for the large changes in the code.

Application

In a simple web pages it changes only the main content, thus, there is no need to reload the entire page. It can be easly changed – whenever you click on the link, AJAX is called, and if JavaScript is not supported, there will be a normal page reloading.

Example

In order to increase the consistency of the code I use jQuery. Suppose you have links to pages as “/path/page.html”. Then just add the following JavaScript code.

  1. $(document).ready(function(){
  2. $('a').live('click', function(){// 'live' ensure that function will be also added to links loaded by using AJAX
  3. var href = $(this).attr('href');// get URL from link
  4. href = href.substring(0, href.length-5)+'.htm';// change extension from 'html' to 'htm'
  5. $('#content').load('http://localhost'+href);// load content to choosen element
  6. return false;// prevent whole page loading
  7. });
  8. });

This code loads a content to element with id=”content”. The content is located at a “/path/page.htm”. Note the extension “html” indicates the entire page, and the “htm” just reloaded fragment.

Server-side code is even simpler. In the case of Apache and PHP, it looks like this:

.htaccess   
  1. RewriteRule ^(.*).html$ index.php?page=$1 [QSA]

In the index.php file, in a place where you should see the content, insert the lines below:

PHP   
  1. <div id="content">
  2. <?php
  3. @readfile($_GET['page'].'.htm');
  4. ?>
  5. </div>

Modifications

You should change the JavaScript function if there are external links, or that which require to load the whole page. You can also add code to change the appearance of the navigation elements to indicate the current subpage.

Benefits

  • The links has untouched code.
  • Content is not duplicated.
  • One version of the page, instead of separate HTML and AJAX.

Leave a Response