-
AJAXifying your site’s navigation
Posted on February 19th, 2009 9 comments
This post is inspired in Refreshing DIV content with AJAX. However this code does not actually automatically refresh the contents of a DIV but it refreshes them when the user clicks a link. The implementation of the code below allows to refresh the contents as mentioned, but the content retrieved can be different every time. This is very useful to make a website work in a similar way as with frames, but with more advantages and without the disadvantages of frames.I provide the code necessary to achieve this purpose but I don’t present it like a step-to-step tutorial. This is because I guess that for anyone with minimal knowledge of HTML and JavaScript is totally self-explanatory and because I would prefer you to make your website look like you want it to rather than like my post tells you to.
You can see a demo page with AJAX navigation here.
Placing the DIVs
First of all, the page needs to have a layout made of DIVs. The picture shows a common structure and it is the one with which the example has been successfully tested. Of course any other type of layout should work too, as what is important is not the distribution of the elements but the presence of DIVs.
Back to the example and the picture: notice the three DIVs have the names shown as ID. So the HTML code for each of them would be:
<!-- Unstyled DIVs. You need CSS to place them in the desired area of the page. --> <div id="top"></div> <div id="left"></div> <div id="content"></div>
The DIVs are of utmost importance, despite their simplicity: taking as reference their ID, they define the area where AJAX will place new contents every time the user clicks a link.
Creating the links
Our idea is to place the navigation links in the left DIV, and show the contents for each of them in the content DIV. In other words, whenever a user clicks a link, the contents of it will be shown in the content DIV, but without reloading the whole page, only this DIV. It can be compared to a page with frames, with the difference that doing it with AJAX is much more flexible and seamlessly integrated.
To place a link, use the code samples:
<a href="javascript: getPage('home.php?','content')">Home</a> <a href="javascript: getPage('page1.php?','content')">Page 1</a> <a href="javascript: getPage('page2.php?','content')">Page 2</a>So why exactly like this? You will notice in the code above that each link is in fact not pointing to a page but to a JavaScript function called getPage(). This function is custom and the code comes below, but for you to know, this is the function which retrieves the content with the help of AJAX. Its structure is as follows: getPage( URL , target ). URL is of course the path to the page to be retrieved, and target is the ID of the DIV where the content will be placed.
It is important you notice that the URL always has to end with a ? or a &. You might have noticed in the three sample links above, that they all end in ?. This is because, as you will see below, we append a timestamp to the end of the URL, as a GET variable. This is to prevent certain browsers (IE) from caching pages fetched with AJAX. Therefore, not ending with a ? or & might make the process not work..
Without the JavaScript it won’t work…
And now, let’s see how does the JavaScript part look like. I recommend placing this between <head> and </head> of the index page (or the page where the links are called from). Alternatively you may include it with the PHP require_once() function.
<script type="text/javascript"> // // AJAX XMLHTTPREQUEST OBJECT // function func_AJAX() { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); return xmlHttp; } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); return xmlHttp; } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); return xmlHttp; } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } } // // Fetch pages with AJAX // function getPage(url,id){ xmlHttp = func_AJAX(); xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState > 0 && xmlHttp.readyState < 4){ document.getElementById(id).innerHTML='Loading...'; } if(xmlHttp.readyState==4){ document.getElementById(id).innerHTML=xmlHttp.responseText; } } goto = url + func_timestamp(); xmlHttp.open("GET",goto,true); xmlHttp.send(null); } // // Generate GET var - UNIX TIMESTAMP // function func_timestamp() { var ts = parseInt(new Date().getTime().toString().substring(0, 10)); return "t="+ts; } </script>I will not go through the code in detail but an overview of it: there are three functions, the first of which is the common xmlHttpRequest object found in every AJAX implementation. The second is the function which actually requests the content to the server, displays a loading message, and once the content has been retrieved from the server, places it in the specified DIV. The third is complementary to the second and merely generates a timestamp as GET variable, which is appended to the end of the URL being requested. Modify the code above to suit your needs.
I hope you like it and that it makes your website even better!
AJAX, Computers & programming, HTML, JavaScript, PHP ajax, asynchronous, code, div, get, html, javascript, layout, links, menu, php, refresh, reload, retrieve, section, update, web 2.0, xml Edit9 responses to “AJAXifying your site’s navigation”
-
Now there’s a working demo available of the code above:
-
Marcio February 28th, 2009 at 19:21
Love it. Really. You know I believe is not that easy to find AJAX examples, because, when you search for AJAX here they come: “the frameworks”. But I like to learn the bases before going to the branches.
Really cool stuff.
I will add this to my favourites and contribute when I know about the subject.Regards.
-
Glad to know you find the resources useful! You’re true when you mention the frameworks; I came across the same difficulties so I had to do my best to learn the basics. Now that I managed to get some knowledge from here and there, I thought I’d share…
Regards and see you around
-
Hello again !
what youve created here is fantastic ! to follow up on your answer at http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_24186976.html , i came across a problem i really dont know how to fix, namely i think my javascript code does not run if passed to div element:
i.e. if you look at this page on its own, it has a vertical line that you can click on (http://research.psychol.cam.ac.uk/~kl278/experiments/questionnaires/LAMstandard.php)
but when that same page is passed to div element, the line disappears and the control does not work – evident when you click the NotWorking radiobutton at http://research.psychol.cam.ac.uk/~kl278/experiments/ES/input.php?Lang=English2
could you please help me get it to work ?
-
Aleix March 5th, 2009 at 00:01
Hello KL,
Cool you like the script and decided to implement it! I’m not sure if I understood well what the problem is, so let me ask at first: javascript code is passed to the DIV means, that the page loaded in the DIV has javascript code in it? Confirm me if its this javascript which experiences problems or if I misunderstood it…
EDIT: ah I see now, the DIV where the content is loaded is “middu”. It works when the page is first loaded because the content is initially loaded directly with Javascript; but changing the DIV content with AJAX makes it no longer appear.
I experienced the same problem today while trying to code a multiple-div layout with AJAX login and unfortunately didn’t find a fix to it yet. It seems to me that – at least with this process – AJAX just retrieves the ‘processed page contents’; as an example, if your external page has < ?php echo "a"; ?> what AJAX will retrieve is a. With Javascript however there’s trouble because it simply doesn’t work – or not found out yet at least how to. To me, a mere alert() in a page loaded to a DIV didn’t show.
Despite recently having not much free time, I am still struggling to get that login to work – and therefore trying to find a workaround. If I find one, I will let you know (other way around if you find it first
)Regards
-
Aleix March 5th, 2009 at 00:21
Okay, a quick Google search produced this link; the user suggests use of iframes to fix this:
http://www.codingforums.com/showthread.php?t=127243 -
i changed to following
var style = “border:0;width:200;height:700;”;
document.getElementById(’middu’).innerHTML= ‘Your browser does not support iframes.’;and the iframe solution seems to work great, thanks !!!
-
oh, see the links for the code change as my comment got stripped
-
Glad to know the iframe worked! It is also good for me to know…
Regards
Leave a reply
-



