Support Forums

Full Version: [TUT] Tabs and Ajax
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I will expand this a little bit, with Ajax.
In this tutorial, I'll show you how to use Ajax with our created Tabs.

Demo (It may not work in all IE versions, because I don't really care about IE)

First thing you'll need are the files from the previous tutorial, which can be found here.

Let me show you how to write an Ajax function with JavaScript.
Code:
var obj = null; // ajax object
var active = null; // this will hold the active tab element

function e(id)
{
    return document.getElementById(id);
}

function changeTab(response)
{
    e("content").innerHTML = response;
}

function init_ajax()
{
    if(window.XMLHttpRequest)
    {
        return new XMLHttpRequest();
    }
    else
    {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

function ajax(url, callback)
{
    if(obj == null)
    {
        obj = init_ajax();
    }
    
    obj.onreadystatechange = function()
    {
        if(obj.readyState == 4 && obj.status == 200)
        {
            callback(obj.responseText);
        }
        else
        {
            callback("Loading");
        }
    }
    obj.open("GET", url, true);
    //obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    obj.send(null);
}

Variable active will be used to hold the object of the current active tab, so we can easily change the tab using javascript.
Function changeTab(), will be used as our callback function, when executing ajax(url, callback)
The function init_ajax() will initialize the XMLHttpRequest Object and return it.
Now on to ajax(url, callback), this is the function that will make the calls and pass on the responses.
At first we check if obj wasn't initialized, if it's still null, in that case we call init_ajax() and pass the return value on to obj.
Next, we declare onreadystate function for our Ajax obj, this will be executed everytime when obj.readyState changes it's value. Rnaging from 0 - 4.
In our case we only need to check if readyState has reached state 4 and we also check if obj.status is 200, just to make sure.
Next line obj.open("GET", url, true), opens a request stream to given url as a GET request.
And finally we use obj.send(null) to send our request, IE requires send() to be called without parameters when sending an GET request.

Now we need to make changes in our PHP script.

Change the following:

PHP Code:
if(isset($_GET['tab']) && !empty($_GET['tab']))
{
    
$page trim(htmlentities($_GET['tab'], ENT_QUOTES));
    
$page = (array_key_exists($page$tabs)) ? $page "home";
}
else
{
    
$page "home";


To this:

PHP Code:
if(isset($_GET['ajax']) && !empty($_GET['ajax']))
{
    
$page trim(htmlentities($_GET['ajax'], ENT_QUOTES));
    
$page = (array_key_exists($page$tabs)) ? $page "home";
    include 
$page.".php";
    die(
$content);
}
elseif(isset(
$_GET['tab']) && !empty($_GET['tab']))
{
    
$page trim(htmlentities($_GET['tab'], ENT_QUOTES));
    
$page = (array_key_exists($page$tabs)) ? $page "home";
}
else
{
    
$page "home";

Now we first check if index.php?ajax was called and do basicalliy the same as in the entire script, the difference is that we fetch content and output it only without executing the rest of the script, using the die() function.

Next we will remove the links from the tabs, as they are not need anymore.
Code:
//// CHANGE THIS
    $link = "<a href=\"index.php?tab={$get}\" title=\"{$title}\">".ucfirst($title)."</a>";
    $class = ($get == $page) ? "active-tab" : "tab";
    $tab_display .= "<div class=\"{$class}\"><div class=\"tab-left\"></div><div class=\"tab-main\">{$link}</div><div class=\"tab-right\"></div></div>";
//// TO THIS
    $link = ucfirst($title);
    $class = ($get == $page) ? "active-tab" : "tab";
    $tab_display .= "<div id=\"{$get}\" onclick=\"ajax('index.php?ajax={$get}', changeTab);active.setAttribute('class', 'tab');active = this;this.setAttribute('class', 'active-tab');\" class=\"{$class}\"><div class=\"tab-left\"></div><div class=\"tab-main\">{$link}</div><div class=\"tab-right\"></div></div>";

We have added new attributes to our div parent, id and an onclick event.
The id helps us to find and store the active tab. The onclick event first executes the ajax function, then changes the attributes on the clicked and active elements, and at last it sets active to the clicked element.
ajax() is being called with the function changeTab as the callback function, this function gets element by id and changes it's inner html.

The last changes are:
PHP Code:
echo <<<TPL
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en-EN" xml:lang="en-EN" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>SupportForums Tutorial - Creating Tabs</title>
        <link rel="stylesheet" type="text/css" href="main.css" />
        <script language="javascript" type="text/javascript" src="ajax.js"></script>
    </head>
    <body onload="active = e('
{$page}');">
        <div class="content-box">
            <div class="tab-parent">
                
{$tab_display}
            </div>
            <div id="content" class="content">
            
{$content}
            </div>
        </div>
    </body>
</html>
TPL; 

We add an onload event to the body element, which sets the active page.
Code:
<body onload="active = e('{$page}');">

And we also add an id to the content div, so our function chnageTab can find it and update it's contents.
Code:
            <div id="content" class="content">
            {$content}
            </div>

That's it the Tabs are now running fully on Ajax.