Bali Web Design Studio is a small enthusiast web design studio based in Bali, Jakarta, Indonesia.

Ajaxify your web pages using Jquery

This simple tutorial example will show you how to dynamically load your web content via ajax instead of default behaviour HTTP request (full round trip), before we continue you may want to have a look at the demo page.

To run this example you need to download jquery library or you can use Google Ajax Libraries API, Next create an HTML page name it “index.html” copy paste the codes below, and change the codes as neccesary:

<html>
<head>
<title>Title</title>
<script type="text/javascript" src="path/to/jquery/jquery.js"></script>
<script type="text/javascript">
// javascript codes goes here
</script>
<style type="text/css">
/* CSS goes here */
/* keep this! */
#loading {display:none;} /*hide the loading element by default*/
</style>
</head>
<body>
<!-- navigation -->
<div id="nav">
<ul>
<!-- current class for the first load page -->
<li><a class="current" href="homepage.html">Home</a></li>
<li><a href="services.html">Services</a></li>
<li><a href="about.html">About me</a></li>
</ul>
</div>
<!-- content holder -->
<div id="wrapper"></div>
</body>
</html>

In this example assumed your website contain of 3 contents homepage, services and about, so here we need to create those pages, simply copy paste the codes below, add the content, and gve a name: homepage.html,about.html, and services.html

<div class="container">
<!-- Content Goes Here ... -->
</div>

No head, no body tags because we already put those tags in index.html and we are simply load these pages into wrapper div at index.html.

Now the main part, we need to write the javascript codes which will handle the ajax request. add these codes to index.html:

//1
$(function () {
//2
function ajaxify(file){
//3
$('<div id="loading"></div>').html("Loading Content: "+file+" ...").appendTo('body').fadeIn();
//4
$.get(file,function(data) {
//5
$("#wrapper").slideUp('slow',function(){
//6
$(this).html(data).slideDown('slow',function(){
//7
$('#loading').fadeOut('slow',function(){$(this).remove();});
});
});
});
}

//8
$("div#nav ul li a").click(function(){
//9
$('#nav ul li a.current').removeClass('current');
//10
$(this).addClass('current');
//11
ajaxify($(this).attr('href'));
//12
return false;
});

//13
ajaxify('homepage.html');

});
  1. The very basic jquery syntax, it tells browser to execute the codes inside the brackets only if the DOM is ready for any modification that going to be made by the scripts
  2. procedure block declaration to handle the onclick method (@ #11 & #13), param (string) the URL to load
  3. create a new div element with class “loading”, add the HTML string into it, then add itself as a child of body, and fade it in (take a look at stylesheet declaration, we set the display attribute to “none”)
  4. create HTTP GET request via ajax, parameter file is the url of the file to load, and on data received …
  5. Slide up the wrapper div and once the slide up effect completed …
  6. Put the data as HTML string into the wrapper div ($(this) refers to wrapper div) then slide it down slowly, and once slide down completed …
  7. Fade out the loading element, and then remove it from the DOM when fade out effect completed
  8. Anchor inside the selector pattern (read the jquery docs about selector) on click …
  9. remove the class current from the element which currently has it
  10. add the current style to the current clicked anchor
  11. execute ajaxify function with parameter the URL (href) of the current clicked anchor
  12. important!, to prevent default behaviour of a link, otherwise it will load the URL with full round trip HTTP request
  13. For the first loaded index.html, tell the browser to load the homepage.html via ajax

!update better approach available here, prevent a fall on screen readers without javascript support also SEO compliants

24 Responses.

  1. Samir January 28, 2012

    Demo page isnt working please check.

  2. Frank September 23, 2011

    JO: i think I had the same problem.

    For some reason get() though that “data” was of the datatype “xml”. When i told get() to expect “html” by adding the dataType parameter after the function everything worked fine :

    $.get(file,function(data) {
    $(“#wrapper”).slideUp(‘slow’,function(){
    $(this).html(data).slideDown(‘slow’,function(){
    $(‘#loading’).fadeOut(‘slow’,function(){$(this).remove();});
    });
    });
    }, “html”);

  3. Jo September 8, 2011

    I tried out this code and it didn’t work. In firefox it displayed the loading:… line but nothing else happened when you clicked the links. In google chrome the links worked but only to display the new url. Meaning, this was the result of clicking the buttons a few times:
    Loading Content: homepage.html …
    Loading Content: about.html …
    Loading Content: services.html …
    Loading Content: homepage.html …
    Loading Content: about.html …
    Loading Content: services.html …
    Loading Content: homepage.html …
    Loading Content: homepage.html …
    Loading Content: services.html .
    I never actually got the real code found in those files. Any ideas?

  4. abercrombie January 15, 2011

    This class and HttpProxy similar, is also used to request remote data, but can be used to cross the primary domain calls, if request used a callback parameters
    Then the server should be appointed by – Type attribute for “sites/javascript”
    And return callback (jsonobject)
    Conversely shall place by – Type attribute for “apply/x – json request directly”
    And direct return json request directly object !

  5. Raghibsuleman December 28, 2010

    its great post…

  6. mitran December 14, 2010

    hey man it really worked for me… thanks for sharing :)

    i`m planning to use it more in my site…

    thanks again…!!!

  7. fooster9090 December 12, 2010

    is the programs always showing the delay and make the read waiting state appear?

  8. Jeff May 29, 2010

    Great article! Using it on my own site now.

    2 issues I faced though:

    1) The loading div doesn’t seem to work properly – it fades in properly enough, but for some reason it doesn’t fade out at all. The function don’t seem to be even read at all.

    2) Is there any ways you can some how add a anchorURL so users can actually use the back button? Right now the URL remains fixed. An anchor URL tutorial would be so awesome! Like instead of services.html the URL will be #services

    Other than that, many thanks for a great and simple AJAX usage tutorial!

    Jeff

  9. Baker May 2, 2010

    Thanks for sharing. Great article.

  10. dwk February 27, 2010

    great work! just what i need, thanks! God Bless!

  11. henri January 4, 2010

    simple but useful.

    Thank for sharing your knowledge.

  12. webmaster April 13, 2009

    the link is updated check it out

  13. JBotte April 8, 2009

    I can’t seem to find the updated page with the seo friendly version and the no js compatibility.

  14. Bassel Khartabil December 31, 2008

    Thank you very much
    I’ll use your method a lot ;-)

  15. Will November 11, 2008

    Nice example! I will try to implement this one on my websystem. Thanks!

  16. Christopher October 13, 2008

    Really this is good information about Ajax.

  17. Komang October 2, 2008

    @Mr.X
    change the click handler:

    $(“div#nav ul li a”).click(function() {
    if(!$(this).hasClass(“current”)) {
    .. load
    }
    return false;
    });

  18. X October 1, 2008

    Hi,

    if you doubleclick the tab preloading text will show forever.
    Is there a way to avoid this?

    Thanks

  19. Komang September 30, 2008

    check out the newer post http://www.chazzuka.com/blog/?p=246 about SEO friendly and accessible ajax, if we have some time, we’ll turn this sample into indexable ajax page

  20. Marius September 27, 2008

    How do search engines open the pages? Will they index them as any other static html?

  21. demonita September 26, 2008

    sure, you can load HTML generated by any server side codes, just change the href target

  22. ghozan September 26, 2008

    can we try it with php? or is there other specific requirements? thanks.

Leave a Reply

bali web design studio Freelance Web Developer Works Bali Web Design Portfolio Get Web Design Quotation RSS Feeds