jquery tablesorter + ajax div content update problem
Asked Answered
T

9

5

I'm having trouble with my tablesorter and ajax div content update. Once the ajax is reloaded all the tablesorter functionalities are lost. I've tried livequery but it doesn't seem to work beyond first listing of the table.

<script type="text/javascript">
    $(document).ready(function(){
        $(".tabs > ul").tabs();
        $("#sortabletable").tablesorter({
            headers: {
                4: { sorter: false },
                5: { sorter: false }
            },
            widgets:['zebra'],
            sortlist:[[0]]
        });
    });
    $("#sortabletable").livequery(function(){
       $(this).tablesorter({
            headers: {
                4: { sorter: false },
                5: { sorter: false }
            },
            widgets:['zebra'],
            sortlist:[[0]]                          
       });
    });

</script>


// The AJAX function...
function AJAX(){
   try{
       xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
       return xmlHttp;
   }
   catch (e){
       try{
           xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
           return xmlHttp;
       }
       catch (e){
           try{
               xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
               return xmlHttp;
           }
           catch (e){
               alert("Your browser does not support AJAX.");
               return false;
           }
       }
   }
}

// Timestamp for preventing IE caching the GET request (common function)
function fetch_unix_timestamp(){
   return parseInt(new Date().getTime().toString().substring(0, 10))
}

////////////////////////////////
//
// Refreshing the DIV TIMEDIV
//
////////////////////////////////

function events_listings(){

   // Customise those settings
   var seconds = 5;
   var divid = "tab01";
   var url = "events_listings.php";

   // Create xmlHttp
   var xmlHttp_one = AJAX();
     // No cache
   var timestamp = fetch_unix_timestamp();
   var nocacheurl = url+"?t="+timestamp;

   // The code...

   xmlHttp_one.onreadystatechange=function(){
       if(xmlHttp_one.readyState==4){
           document.getElementById(divid).innerHTML=xmlHttp_one.responseText;
           setTimeout('events_listings()',seconds*1000);
       }
   }
   xmlHttp_one.open("GET",nocacheurl,true);
   xmlHttp_one.send(null);
}

// Start the refreshing process
window.onload = function startrefresh(){
   setTimeout('events_listings()',seconds*1000);
}

////////////////////////////////
//
// Refreshing the DIV TIMEINWASHINGTON
//
////////////////////////////////
var formvar = "";
function view_job(temp){

   // Customise those settings
   var seconds = 8;
   var divid = "tab02";
   var url = "view_job.php";
   formvar = temp;

   // Create xmlHttp
   var xmlHttp_two = AJAX();

   // No cache
   var timestamp = fetch_unix_timestamp();
   var nocacheurl = url+"?t="+timestamp+"&"+formvar;
       // The code...
   xmlHttp_two.onreadystatechange=function(){
       if(xmlHttp_two.readyState==4){
           document.getElementById(divid).innerHTML=xmlHttp_two.responseText;
           setTimeout('view_job(formvar)',seconds*1000);
       }
   }
   xmlHttp_two.open("GET",nocacheurl,true);
   xmlHttp_two.send(null);
}

// Start the refreshing process
window.onload = function startrefresh(){
   setTimeout('view_job(formvar)',seconds*1000);
} 
Teat answered 5/4, 2009 at 3:47 Comment(0)
S
7

After loading the result, you need to do $("#table").tablesorter() once more to re-sort it. Also, rather than writing your ajax code by hand, use $.get or $.post from jquery

Specimen answered 5/4, 2009 at 4:30 Comment(2)
thanks mate. i just figured that out, and using jquery .ajax now. it works perfectly.Teat
calling the trigger() method should work, as per my answer. I suspect it may have less overhead than calling .tablesorter().Dayan
D
24

Instead of calling .tablesorter() again, you can trigger an update instead, without any of the overhead of calling .tablesorter():

("#table").trigger("update");

I've used this successfully in my own project. You can make the trigger() call in your :success handler.

HTH

Dayan answered 3/7, 2009 at 19:38 Comment(3)
Thanks. Thats really helpful! If writing a custom parser, make sure that it returns the correct type (numeric or text) otherwise this won't work for that column.Russi
In my project after updating the table body, once I clicked on any column's sorter, it replaced the body with the last content. But using this solution (trigger("update")) worked like a charm. ThanksMorell
I have tried this option but it does not work for me. The new instantiation does, meaning $("#xxx").tablesorter();Garotte
S
7

After loading the result, you need to do $("#table").tablesorter() once more to re-sort it. Also, rather than writing your ajax code by hand, use $.get or $.post from jquery

Specimen answered 5/4, 2009 at 4:30 Comment(2)
thanks mate. i just figured that out, and using jquery .ajax now. it works perfectly.Teat
calling the trigger() method should work, as per my answer. I suspect it may have less overhead than calling .tablesorter().Dayan
C
2

Your original issue was that Live Query can only detect changes to the document that started with a jQuery call.

Directly setting innerHTML will not cause it to fire. Changing that line to $("#"+divid).html(xmlHttp_one.responseText) would have solved your problem.

I'm glad to hear that you found a solution! Be aware, however, that Live Query has to scan the document every time it is modified — which is convenient but comes with a big performance hit. It would be better to put the call to tablesorter() in your jQuery.ajax(success:) function.

Chanukah answered 5/4, 2009 at 5:35 Comment(1)
Thank you very much for that idea Sidney. I have updated my code now, with call for tablesorter inside success: , and its much better execution, and eliminated the flickering caused by livequery. thankx again.Teat
H
2

I had the same problem and found this method.

$("#table tbody tr").addClass("to-delete");
$("#table tbody").append(data);
$("#table").trigger("update");
$("#table").trigger("appendCache");
$("#table").trigger("sorton",[[[2,1],[0,0]]]);
$("#table tbody tr.to-delete").remove();
$("#table").trigger("update");

It's not very pretty but it works!

Harbird answered 26/9, 2011 at 4:55 Comment(0)
T
1

Found a solution by using jQuery .ajax function. much easier, and works perfectly.

Teat answered 5/4, 2009 at 4:36 Comment(0)
S
1

As mentioned using the jquery AJAX call is the best way to go :P but I found the post to be a bit vague for newbies so here's the code that i used in my project:

    $('input.user').click(function() {
    var getContact = $(this).val();
    $.ajax({
        url: 'contact_table.php',
        data: 'userID='+getContacts,
        success: function(result) {
            $('#UserContactTable').append(result);
            $("#contact-list").tablesorter();
        }
    });
});
Sanson answered 29/8, 2009 at 16:58 Comment(0)
C
1

Use the ajaxStop function and the code will run after the ajax call is complete.

$("#DivBeingUpdated").ajaxStop(function(){ 
    $("table").tablesorter()
});
Coblenz answered 11/2, 2012 at 18:39 Comment(0)
H
0

I am quite new in java/ajax programming, but have exactly the same problem - when I update the content of a div (using ajax) with my table, tablesorter does not function. If I load the table directly to the very first page (not into a div), tablesorter works perfectly.

So, I would be greatful if you can explain in more details how exactly you modified your code to solve it.

Thanks, Bojan

Hardnett answered 11/6, 2009 at 20:7 Comment(0)
L
0

The answer is irrelevant to the question asked but it might help someone.

In case of loading table contents via AJAX call the function tablesorter() must be called after successful execution of AJAX call. Code that explains the same -->

        $(document).ready(function(){
        //once the document is loaded make the AJAX call to required url
        $.ajax({
            url : 'nutrition.xml',  //I have accessed nutrition.xml file
            type : 'GET',
            dataType : 'xml'    //return type is xml
        })
        .done(function(xml){
            //after successful call
            /*here i have created an html string but,
            one call also use appendTo() like : 
            $("<thead></thead>").appendTo("table"); and so on.. */

            var str = "<thead><tr><th>Name</th><th>Calories</th></tr></thead><tbody>";

            //loop through each element of xml filer
            $(xml).find('food').each(function(i){
                var name = $(this).find('name').text();
                var calories = $(this).find('calories').attr('total');
                //append to string
                str = str + "<tr><td>"+name+"</td><td>"+calories+"</td></tr>";
            });
            str = str + "</tbody>";
            //set html for <table>
            $("table").html(str);

            //the main part call tablesorter() once contents are set successfully
            $("table").tablesorter({debug: true}); 
        })
        .fail(function(xhr,status,errorThrown){
            //on ajax call failure
            alert("An error occurred while processing XML file.");
        });         
    });

The contents of nutrition.xml file :

<?xml version="1.0"?>
    <nutrition>
    <food>
        <name>Avocado Dip</name>
        <calories total="110" fat="100"/>
    </food>
    <food>
        <name>Bagels, New York Style </name>
        <calories total="300" fat="35"/>
    </food>
    <food>
        <name>Beef Frankfurter, Quarter Pound </name>
        <calories total="370" fat="290"/>
    </food>
    </nutrition>
Luetic answered 17/3, 2016 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.