Name Mon Lu

Love jQuery/CSS

Blog about Webdev

Twitter supawaza

RSS Twitter Flickr

What I am up to:


Ver­sion in this arti­cle: jQuery 1.3.2 / CSV2Table 0.03-b-2.9

Lately I started to like CSV (Com­mon Sep­a­rated Val­ues) more and more com­par­ing to XML.XML is a pain to setup even as enter­ing data, then grab­bing the data requires Einstein’s brain plus 3 sleep­less and hair-pulling days of cod­ing… okay, I maybe exag­ger­ated a bit, but that’s how I feel about XML. My first encounter with CSV was InDe­sign, in there, you can import a bunch of data and gen­er­ates PDF like Word’s Mail Merge fea­ture. Then one day, some­one asked me if I can find a bet­ter and eas­ier way to help the non web peo­ple to main­tain a site. I started out with search terms like “jQuery read text files” or some­thing like that, one of the results returned as using CSV and there is a plu­gin called CSV2Table in the jQuery Plu­g­ins web­site by Toshiro Taka­hashi writ­ten ear­lier this year. Test­ing… test­ing… and hot damned! It’s like magic!!!

The awe­some thing about CSV is you can enter all the data using Excel, then sim­ply save the file as something.csv and it’s ready to be used. No stu­pid header <xml></xml> tags, inner tags, child tags or what­ever the heck tags. Just sim­ple data. If you really, really want to be fancy; you can even add HTML such as <img> – believe it not, it worked like a charm. Although, it’s silly to for­mat your CSV data within while you have your hands on the god-awsome jQuery frame­work to manip­u­late all of those data. Then to gen­er­ate the table, all you sim­ply have to do is:

	$(document).ready(function(){
    	$("#div").csv2table(csvfile,{ <em>options</em> });
    });

Well, I’m not going to get into the options detail but you can refer back to the CSV2Table docs. You can manip­u­late how the data dis­play, for­mat, col­orize, draw a dragon or what­ever. This plu­gin is very flex­i­ble when it comes to for­mat­ting the results. Some peo­ple describe me as lazy, but I like to describe myself as “effi­cient” because I don’t like to repeat myself or do extra work. So it doesn’t make sense to write the code above every­time I need to reuse it, that’s just not the Mon’s way, here’s Mon’s way:

	function csvReader(container,csvfile){
			$(container).csv2table(csvfile,{
				sortable: true,
				removeDoubleQuote : true,
				nowloadingMsg: "Loading "+$("#eblastsYear").val()+" eblasts archive...",
				errorMsg : "Error loading "+$("#eblastsYear").val()+" eBlasts archive. Archive either doesn't exist or renamed. Please contact Mon (mlu@equuscs.com) for support.",
				onload : function(id,op,data,ary){
					$("#totalEblasts").text(ary.length-1); //Display the total rows of the eblasts
					$(container+' tr:even').css('background','#efefef'); //Every even row gets colorized
					$(container+' th').css({"text-align":"left"}); //Just setting the TH rows will be left aligned
				 }
			});
		}

I wrote a func­tion that because I know I’m going to reuse the code to load the exact same data, just maybe the CSV file or the DIV con­tainer might be dif­fer­ent. Instead of writ­ing re-writing again. If I ever need it, all I have to do is:

	csvReader("#csvContainer","data.csv");

Done. Now, you prob­a­bly won­der, what the heck did I use it for? Well, see screenshot:

csv

So when the user clicks on “View Archive”, it loads a new CSV file like this:

$("#selectYear").live('click',function(){
    csvReader("#csv","eblasts/"+$("#eblastsYear").val()+".csv");
});

Less work = bet­ter. One minor thing I felt miss­ing was when the file is miss­ing or failed to load, it just get stuck on the default “Now load­ing” mes­sage. I dug under the hood of the CSV2table codes, it uses $.get() to process the data which doesn’t really can tell whether the XHR request was suc­cess­ful or not; nor it can detect it unless you add the ajax.error() han­dle. So I’ve decided to change it to using the actual $.ajax() to call the data, and detect if there is a 404 error, it’ll dis­play an error mes­sage accord­ingly instead of just “Load­ing…” – while I was at it, I felt, well, I and I’m pretty sure most peo­ple want to cus­tomize their sucess­ful load and error mes­sages, right? So I added two more set­tings inside the plu­gin which are: nowload­ingMsg and errorMsg. If you are so darn lazy and don’t want to cus­tomize it, it defaults to “Now load­ing…” (fades out) and “CSV file not found.”. Here’s the modifications:

	op = $.csv2table.setting[id] = $.extend({
			url                : url,
			nowloadingImg      : $.csv2table.loadImg,              //Image of now loading...
			nowloadingMsg      : null,     						   //Message of now loading...
			errorMsg		   : null,							   //Error Message
       	// The rest of the codes...

Do a search for “op.nowloadImg” and you’ll see “$.get()”. I mod­i­fied as fol­low around line 130 if you added what’s above:

	//Default loading message if not set in settings
    if(op.nowloadingMsg == null){ op.nowloadingMsg = "Now loading..."; }
    $(contents).before('
<div class="csv2table-loading"><img src="'+op.nowloadingImg+'" alt="" /> '+op.nowloadingMsg+'</div>
' )
 
    //Default error message
    if(op.errorMsg == null){ op.errorMsg = "CSV file not found."; }
 
    $.ajax({
       type: "GET",
       url: url+"?"+(new Date()).getTime(),
       data: $.csv2table.data[id],
       success: function(data,textSatus){
         $(".csv2table-loading").hide();
         $(".csv2table-loading").remove();
         $(contents).css("display","none").html(mkRowsAry(id,data));
         setCSS(id);
         $(contents).fadeIn();
         if(op.use_api=='jqchart'){
            if(op.use_api_type=='jqchart:line')op.type=$.csv2table.setting[id].type='line';
            else if(op.use_api_type=='jqchart:bar')op.type=$.csv2table.setting[id].type='bar';
            useChart(id,op,data,$.csv2table._rowsAry[id]);
         }
         if($.csv2table.setting[id].onload)$.csv2table.setting[id].onload(id,op,data,$.csv2table._rowsAry[id]);
       },
       error : function (xhr, e) {
          if (xhr.status == 404) {
            // page not found
            $(".csv2table-loading").addClass("csv2table_error").text(op.errorMsg);
          }
        }
    });

To sum it up for the CSV2Table mod, these are the changes I’ve made:

  • 2 extra set­tings: nowload­ingMsg / errorMsg (defaults to “Now load­ing…” and “CSV file not found.”)
  • Changed $.get() method to $.ajax()
  • Added 1 extra CSS class: csv2table_error

My mod­ded: jquery.csv2table-mod

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • email
  • Ping.fm
  • Reddit
  • RSS
  • StumbleUpon
  • Technorati
  • Twitter

Related Posts

No related posts.

This entry was posted on Wednesday, October 21st, 2009 at 6:02 PM and is filed under Web Dev. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

No Responses to “jQuery CSV2Table — Modified”