Pages

Tuesday, January 3, 2012

Simple Ajax Tab Menu


Ajax tab menu is very useful to show contents without reloading the full page. Last week i create a Ajax based tab menu. Basically i modified my menu by getting help from this link. Here i'll show the steps that i do to create this menu functional.
1. create a simple html file (index.html). Between body tag put these

    <ul id="tabmenu">
    <li onclick="makeactive(1)"><a class="" id="tab1">First Tab</a></li>
    <li onclick="makeactive(2)"><a class="" id="tab2">Second Tab</a></li>
    <li onclick="makeactive(3)"><a class="" id="tab3">Third Tab</a></li>
    </ul>
    <div id="content"></div>

Between head tag put these lines



    <script language="JavaScript" type="text/javascript" src="ajax.js"></script>
    <script language="JavaScript" type="text/javascript">
    function makeactive(tab)
    {
    document.getElementById("tab1").className = "";
    document.getElementById("tab2").className = "";
    document.getElementById("tab3").className = "";
    document.getElementById("tab"+tab).className = "active";
    callAjax('content.php?content= '+tab, 'content', 'getting content for tab '+tab+'. Wait...', 'Error');
    }
    </script>

2. Now create the ajax.js that we add in our head section. These are the content of ajax.js

    function callAjax(url, pageElement, callMessage, errorMessage) {
    document.getElementById(pageElement).innerHTML = callMessage;
    try {
    req = new XMLHttpRequest(); /* e.g. Firefox */
    } catch(e) {
    try {
    req = new ActiveXObject("Msxml2.XMLHTTP"); /* some versions IE */
    } catch (e) {
    try {
    req = new ActiveXObject("Microsoft.XMLHTTP"); /* some versions IE */
    } catch (E) {
    req = false;
    }
    }
    }
    req.onreadystatechange = function() {responseAjax(pageElement, errorMessage);};
    req.open("GET",url,true);
    req.send(null);
    }
    function responseAjax(pageElement, errorMessage) {
    var output = '';
    if(req.readyState == 4) {
    if(req.status == 200) {
    output = req.responseText;
    document.getElementById(pageElement).innerHTML = output;
    } else {
    document.getElementById(pageElement).innerHTML = errorMessage+"\n"+output;
    }
    }
    }

3. Now we need another php file where output will be processed. Nmae it "content.php" and put these lines in it

    <?php
    if ($_GET['content'] == 1)
    {
    echo 'Content for Page 1';
    }
    if ($_GET['content'] == 2)
    {
    echo 'Content for Page 2';
    }
    if ($_GET['content'] == 3)
    {
    echo 'Content For Page 3';
    }
    ?>

Thats all. Now run the index file and see the tab menu in action.
To get First Tab selected when the page loaded just add this( onload="makeactive(1)") to body tag. So in index.html body tag will look as like as that : <body onload="makeactive(1)">

ස‍ටහන