Version in this article: jQuery 1.3.2 / CSV2Table 0.03-b-2.9
Lately I started to like CSV (Common Separated Values) more and more comparing to XML.XML is a pain to setup even as entering data, then grabbing the data requires Einstein’s brain plus 3 sleepless and hair-pulling days of coding… okay, I maybe exaggerated a bit, but that’s how I feel about XML. My first encounter with CSV was InDesign, in there, you can import a bunch of data and generates PDF like Word’s Mail Merge feature. Then one day, someone asked me if I can find a better and easier way to help the non web people to maintain a site. I started out with search terms like “jQuery read text files” or something like that, one of the results returned as using CSV and there is a plugin called CSV2Table in the jQuery Plugins website by Toshiro Takahashi written earlier this year. Testing… testing… and hot damned! It’s like magic!!!
The awesome thing about CSV is you can enter all the data using Excel, then simply save the file as something.csv and it’s ready to be used. No stupid header <xml></xml> tags, inner tags, child tags or whatever the heck tags. Just simple 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 format your CSV data within while you have your hands on the god-awsome jQuery framework to manipulate all of those data. Then to generate the table, all you simply 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 manipulate how the data display, format, colorize, draw a dragon or whatever. This plugin is very flexible when it comes to formatting the results. Some people describe me as lazy, but I like to describe myself as “efficient” because I don’t like to repeat myself or do extra work. So it doesn’t make sense to write the code above everytime 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 function 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 container might be different. Instead of writing re-writing again. If I ever need it, all I have to do is:
csvReader("#csvContainer","data.csv");
Done. Now, you probably wonder, what the heck did I use it for? Well, see screenshot:
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 = better. One minor thing I felt missing was when the file is missing or failed to load, it just get stuck on the default “Now loading” message. 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 successful or not; nor it can detect it unless you add the ajax.error() handle. 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 display an error message accordingly instead of just “Loading…” – while I was at it, I felt, well, I and I’m pretty sure most people want to customize their sucessful load and error messages, right? So I added two more settings inside the plugin which are: nowloadingMsg and errorMsg. If you are so darn lazy and don’t want to customize it, it defaults to “Now loading…” (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 modified as follow 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 settings: nowloadingMsg / errorMsg (defaults to “Now loading…” and “CSV file not found.”)
- Changed $.get() method to $.ajax()
- Added 1 extra CSS class: csv2table_error
My modded: jquery.csv2table-mod
Related Posts
No related posts.

No Responses to “jQuery CSV2Table — Modified”