A simple AJAX website with jQuery

A simple AJAX website with jQuery

Posted on Sep 7th, 2009

Introduction

This time we are going to create a simple AJAX website with jQuery and the right amount of PHP & CSS. It is going to have a few pages loaded by AJAX from the PHP back-end, and a complete support of the browser history – a real pain for any AJAX or Flash site .

So get the demo files and lets start rollin’.

The XHTML

First, we create the XHTML backbone of the site.

demo.html

01 <div id="rounded">
02
03 <img src="img/top_bg.gif" /><!-- image with rounded left and right top corners -->
04 <div id="main" class="container"><!-- our main container element -->
05
06 <h1>A simple AJAX driven jQuery website</h1> <!-- titles -->
07 <h2>Because simpler is better</h2>
08
09 <ul id="navigation"> <!-- the navigation menu -->
10 <li><a href="#page1">Page 1</a></li> <!-- a few navigation buttons -->
11 <li><a href="#page2">Page 2</a></li>
12 <li><a href="#page3">Page 3</a></li>
13 <li><a href="#page4">Page 4</a></li>
14 <li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li> <!-- rotating gif - hidden by default -->
15 </ul>
16
17 <div class="clear"></div> <!-- the above links are floated - we have to use the clearfix hack -->
18
19 <div id="pageContent"> <!-- this is where our AJAX-ed content goes -->
20 Hello, this is the default content
21 </div>
22
23 </div>
24
25 <div class="clear"></div> <!-- clearing just in case -->
26
27 <img src="img/bottom_bg.gif" /> <!-- the bottom two rounded corners of the page -->
28
29 </div>

This code is positioned in the body part of our demo.html file. Its main purpose is to serve as a front-end to the php back-end, with jQuery handling all the communication in between.

Note the addresses of the navigation links – #page and a page number. This part, called a hash, is included in the current URL without a page refresh, creating an entry in the browser’s history. By monitoring this hash with javascript, we can change the loaded page by AJAX and provide a seamless browsing experience.

Our simple AJAX enabled jQuery website

Our simple AJAX enabled jQuery website

The CSS

Lets take a look at our style sheet.

demo.css

01 body,h1,h2,h3,p,td,quote,
02 small,form,input,ul,li,ol,label{    /* resetting our page elements */
03     margin:0px;
04     padding:0px;
05     font-family:Arial, Helvetica, sans-serif;
06 }
07
08 body{   /* styling the body */
09     margin-top:20px;
10     color:#51555C;
11     font-size:13px;
12     background-color:#123456;
13 }
14
15 .clear{ /* the clearfix hack */
16     clear:both;
17 }
18
19 a, a:visited {  /* styling the links */
20     color:#007bc4;
21     text-decoration:none;
22     outline:none;
23 }
24
25 a:hover{    /* the hover effect */
26     text-decoration:underline;
27 }
28
29 #rounded{   /* the outermost div element */
30     width:800px;
31     margin:20px auto;   /*center it on the page*/
32 }
33
34 .container{ /* this one contains our navigation, titles, and fetched content */
35     background-color:#FFFFFF;
36     padding:10px 20px 20px 20px;
37 }
38
39 h1{ /* the heading */
40     font-size:28px;
41     font-weight:bold;
42     font-family:"Trebuchet MS",Arial, Helvetica, sans-serif;
43 }
44
45 h2{ /* the subheading */
46     font-weight:normal;
47     font-size:20px;
48
49     color:#999999;
50 }
51
52 ul{ /* the unordered list used in the navigation */
53     margin:30px 0px;
54 }
55
56 li{ /* we float the li-s, which contain our navigation links - we later apply clearfix */
57     list-style:none;
58     display:block;
59     float:left;
60     width:70px;
61 }
62
63 li a,li a:visited{  /* the navigation links */
64     padding:5px 10px;
65     text-align:center;
66     background-color:#000033;
67     color:white;
68
69     -moz-border-radius:5px; /* rounding them */
70     -khtml-border-radius: 5px;
71     -webkit-border-radius: 5px;
72     border-radius:5px;
73
74 }
75
76 li a:hover{
77     background-color:#666666;
78     text-decoration:none;
79 }
80
81 #pageContent{   /* the container that holds our AJAX loaded content */
82     margin-top:20px;
83
84     border:1px dashed #cccccc;
85     padding:10px;
86
87     -moz-border-radius: 5px;    /* rounding the element */
88     -khtml-border-radius: 5px;
89     -webkit-border-radius: 5px;
90     border-radius: 5px;
91 }
92
93 #loading{   /* hiding the rotating gif graphic by default */
94     visibility:hidden;
95 }

An important reminder would be to note that rounding corners with CSS is only supported in the latest versions of Firefox, Safari and Chrome.

The jQuery source

To complement the front-end, here is the script that drives the site.

script.js

01 $(document).ready(function(){   //executed after the page has loaded
02
03     checkURL(); //check if the URL has a reference to a page and load it
04
05     $('ul li a').click(function (e){    //traverse through all our navigation links..
06
07             checkURL(this.hash);    //.. and assign them a new onclick event, using their own hash as a parameter (#page1 for example)
08
09     });
10
11     setInterval("checkURL()",250);  //check for a change in the URL every 250 ms to detect if the history buttons have been used
12
13 });
14
15 var lasturl=""; //here we store the current URL hash
16
17 function checkURL(hash)
18 {
19     if(!hash) hash=window.location.hash;    //if no parameter is provided, use the hash value from the current address
20
21     if(hash != lasturl) // if the hash value has changed
22     {
23         lasturl=hash;   //update the current hash
24         loadPage(hash); // and load the new page
25     }
26 }
27
28 function loadPage(url)  //the function that loads pages via AJAX
29 {
30     url=url.replace('#page','');    //strip the #page part of the hash and leave only the page number
31
32     $('#loading').css('visibility','visible');  //show the rotating gif animation
33
34     $.ajax({    //create an ajax request to load_page.php
35         type: "POST",
36         url: "load_page.php",
37         data: 'page='+url,  //with the page number as a parameter
38         dataType: "html",   //expect html to be returned
39         success: function(msg){
40
41             if(parseInt(msg)!=0)    //if no errors
42             {
43                 $('#pageContent').html(msg);    //load the returned html into pageContet
44                 $('#loading').css('visibility','hidden');   //and hide the rotating gif
45             }
46         }
47
48     });
49
50 }

Note how, on line 3, we call the checkURL() function as soon as the page finishes loading – this way we insure that, if a link to an inner page on the site has been shared and a new visitor visits it, the site will fetch the required page and show it when the page is loaded.

As you can see on line 11, we setup an interval for checkURL() to check the browser’s address 4 times a second in order to detect any possible changes arising from the use of the back/forward buttons.

Now lets take a look at the back-end.

The PHP

The PHP back-end is just a few lines of code and is the place to start, if you want to customize this example.

load_file.php

1 if(!$_POST['page']) die("0");
2
3 $page = (int)$_POST['page'];
4
5 if(file_exists('pages/page_'.$page.'.html'))
6 echo file_get_contents('pages/page_'.$page.'.html');
7
8 else echo 'There is no such page!';

It basically checks whether the variable $_POST[‘page’] is set, and if it is, checks whether the respective page_.html file exists, and outputs it back to jQuery.

You can improve upon this by fetching data from a database, by using sessions, or displaying a folder of images – anything you might have on your mind.

Conclusion

Today we created a simple, customization-ready, AJAX enabled web site. Feel free to use the code and the techniques that were demonstrated in any of your projects.

Advertisements
By Rz Rasel Posted in jQuery

Leave a Reply

Fill in your details below or click an icon to log in:

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