Abhishek Biswal
Abhishek Biswal

Reputation: 450

jQuery Tabs : Load Data when Tab is Active using AJAX

Here is my problem:

The Problem

I have created Tabs using jQuery which is very similar to that of jQueryUI or Twitter Bootstraps's Tabs. There are 3 Tabs on page: "Today", "This Week", "This Month". When you click on "Today" tab, you'll see all the posts submitted today. And other 2 tabs work similarly. It's working, all the data loads but I don't want the users to wait for the data to take so much time to load. (If there are 10 posts under each tab, then the page is loading 30 posts), to save their time, I want to use jQuery AJAX to fetch the posts when a specific tab is active, or in simple words, when a user clicks on the tab, the posts should load using AJAX.

What I am Thinking

Yes, I know I can create 3 different pages for that, but how should I load the data using AJAX when the Tab is clicked? Here is my HTML (with javascript) Code:

<script type="text/javascript">

$(document).ready(function() {

    //When page loads...
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li").click(function() {

        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content

        var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active ID content
        return false;
    });

});

</script>

<ul class="tabs">
    <li><a href="#today">Today</a></li>
    <li><a href="#week">This Week</a></li>
    <li><a href="#month">This Month</a></li>
</ul>

<div class="tab_container">

<div id="today" class="tab_content">
       <!--Load the Content from today.php-->
</div>

<div id="week" class="tab_content">
       <!--Load the Content from week.php-->
</div>

<div id="month" class="tab_content">
       <!--Load the Content from month.php-->
</div>

</div>

More Info

Upvotes: 1

Views: 8744

Answers (2)

Man, this is a tricky question. Is it necessary to load this data through AJAX? If the user disables JS, he won't see anything o.O

If I were you, I would firstly load all the data without AJAX, then create an interval to reload everything, because I think the data won't be updated every 5 seconds, for example, so it isn't necessary to make a request everytime an user clicks.

The JSON data format can help because you will request a single page, then you can send the results (in this case, 3 items: today, thisWeek, thisMonth) as a single JSON string, and finally print it out.

Example of the JSON response of the PHP page (take a look at json_encode (PHP Manual))

{
    today:{
        title:'Title',
        content:'Content',
        url:'http://www.site.com/url.php'
    },
    week:{
        title:'Title',
        content:'Content',
        url:'http://www.site.com/url.php'
    },
    month:{
        title:'Title',
        content:'Content',
        url:'http://www.site.com/url.php'
    }
}

A draft of the jQuery code (jQuery.getJSON()):

// when page loads...
setInterval(function () {
    $.getJSON('getNewPosts.php', function (data) {
        // now you should print each JSON object to it's respective DIV
    }
}, 30000); // 30 seconds

Upvotes: 1

Matt Farmer
Matt Farmer

Reputation: 709

It seems to me the following modification would work for you. In this scenario, jQuery POSTs to some URL you choose if the active tab's content is empty, and then retrieves whatever HTML comes down from the server a drops it inside the active tab asynchronously.

You'll need to change some of the parameters inside the $.ajax call, but other than that - it should work.

<script type="text/javascript">

$(document).ready(function() {

    //When page loads...
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li").click(function() {

        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content

        var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content

        if($(activeTab).html() == '') {
          $.ajax({
            url: '/url/to/post',
            type: 'post',
            dataType: 'html',
            success: function(content) {
              $(activeTab).html(content);
            }
          });
        }

        $(activeTab).fadeIn(); //Fade in the active ID content
        return false;
    });

});

</script>

Upvotes: 2

Related Questions