tech @ Beacon Deacon

A DataTable with AJAX - Jamie Johnson

Jamie Johnson

June 14, 2017

Last year, I wrote multiple articles about SpryMedia's DataTables Table plug-in for jQuery and various features or functions thereof, including how to use my own scripts to further extend the use of the plug-in. In this article, I am going to show how to use AJAX with DataTables.

Back in the day, one might have done something like this:

var mesa = $('.datatable').DataTable();
// start AJAX
var xmlhttp;
xmlFile = "batman.xml";

if (window.XMLHttpRequest){// code for IE, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
  if (xmlhttp.readyState==4)
  {
    if(xmlhttp.status==200)
    {
        var xmlStringFull = xmlhttp.responseText;
        items=xmlStringFull;
        items=items.toString();
        items=items.split("");
        whatever=""; // due to strict XML in codespace
        i=1; // skip first array element as it is not an item element
        itemsoutput='';
        itemsquantity = Math.min(101,items.length); // cap at 100 items plus the 1 ignored unless the items array has less elements
        while(i!=itemsquantity){
            itemalias=items[i];
            itemalias=itemalias.split("");
            itemalias=itemalias[1];
            itemalias=itemalias.toString();
            itemalias=itemalias.split("");
            itemalias=itemalias[0];
            itemalias=itemalias.toString();
            itemname=items[i];
            itemname=itemname.split("");
            itemname=itemname[1];
            itemname=itemname.toString();
            itemname=itemname.split("");
            itemname=itemname[0];
			itemgender=items[i];
            itemgender=itemgender.split("");
            itemgender=itemgender[1];
            itemgender=itemgender.toString();
            itemgender=itemgender.split("");
            itemgender=itemgender[0];
			itemappeared=items[i];
            itemappeared=itemappeared.split("");
            itemappeared=itemappeared[1];
            itemappeared=itemappeared.toString();
            itemappeared=itemappeared.split("");
            itemappeared=itemappeared[0];
			
			mesa.row.add({
				"alias": itemalias,
				"name": itemname,
				"gender": itemgender,
				"appeared": itemappeared
			}).draw();
			
            itemalias='';
            itemname='';
            itemgender='';
			itemappeared='';
            i++;
        }
        if(i==1){ //placeholder if needed
        } else { //placeholder if needed
        } //end placeholder if needed
    }
  }
}  
xmlhttp.open("GET",xmlFile,true);

xmlhttp.send();
// end AJAX
    

However, there is a much better way with less code. Consider the below DataTable using AJAX below:


Alias Name Gender Appeared

First the bad news...

The DataTables plug-in does not truly use the "X" in AJAX. That is, it does not use XML. Rather, it uses alternatives to straight XML data. Because of that, the solution was not a straightforward AJAX implementation. I opted to use AJAX data source objects. At a glance, the objects text file (batman.txt in my example) is the data source. The file is minified, but here is the data in a friendlier display:

{
	"data": [
		{
			"alias": "Mr. Freeze",
			"name": "Dr. Victor Fries",
			"gender": "Male",
			"appeared": "1959"
		},
		{
			"alias": "Poison Ivy",
			"name": "Pamela Lillian Isley",
			"gender": "Female",
			"appeared": "1966"
		},
		{
			"alias": "The Penguin",
			"name": "Oswald Chesterfield Cobblepot",
			"gender": "Male",
			"appeared": "1941"
		},
		{
			"alias": "The Joker",
			"name": "Jack Napier (according to some)",
			"gender": "Male",
			"appeared": "1940"
		},
		{
			"alias": "Harley Quinn",
			"name": "Dr. Harleen Frances Quinzel",
			"gender": "Female",
			"appeared": "1992"
		},
		{
			"alias": "Mad Hatter",
			"name": "Jervis Tetch",
			"gender": "Male",
			"appeared": "1948"
		},
		{
			"alias": "The Riddler",
			"name": "Edward Nygma/Nigma or Nashton",
			"gender": "Male",
			"appeared": "1948"
		},
		{
			"alias": "Catwoman",
			"name": "Selina Kyle",
			"gender": "Female",
			"appeared": "1940"
		},
		{
			"alias": "Two-Face",
			"name": "Harvey Dent",
			"gender": "Male",
			"appeared": 
			"1942"
		}
	]
}

However, I really wanted to use XML (batman.xml in my example). Now for the sake of this example, I did end up using a static batman.txt file (a minified version of what is displayed above). However, I recommend using a Perl CGI or some other server-side script to dynamically generate the text file from the batman.xml file and referring to the CGI script instead of the text file in the JavaScript. This way, one can update XML instead of a text file or one can read in RSS or some other XML and with a little massaging from a server-side script, one can have it output as if it were a text file in the format seen above. My Perl CGI script to accomplish this is here (Note that you would want to rename it and place it on your server where such scripts can run and not use a .txt extension, which I used so you could see the code in the script.

Now the good news...

The good news is that the above DataTable using AJAX is responsive and takes much less coding to implement. Here's the code (and I have made assets linkable for your convenience):

<script type="text/javascript" src="datatable/jquery-1.12.0.min.js"></script>
<link rel="stylesheet" type="text/css" href="datatable/datatables.min.css"/>
<script type="text/javascript" src="datatable/datatables.min.js"></script>
<table cellpadding="0" cellspacing="0" border="0" class="display datatable">

<thead>
    <tr class="dropdown">
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    
    <tr>
        <th>Alias</th>
        <td>Name</td>
        <td>Gender</td>
        <td>Appeared</td>
    </tr>

</thead>
<tbody id="itemsoutput">
</tbody>
</table>
<style type="text/css">
    <!--
.dataTables_filter { position: relative; left: -40px; }
-->
</style>
<script type="text/javascript">
$(document).ready(function() {
    var mesa = $('.datatable').DataTable( { 
        responsive: true,
        ajax: "http://tech.beacondeacon.com/batman.txt",// It would make since to generate this dynamically from XML with a server-side language like perl. For this example, I am using a static file.  However, here is a perl script to  do it: batmandata.cgi
        columns: [
            { data: 'alias' },
            { data: 'name' },
            { data: 'gender' },
            { data: 'appeared' }
        ]
    } );
} );
$( window ).resize(function() { 
  $('.datatable').removeAttr('style');
}); 
</script>
<style type="text/css">
<!--
@media all and (min-width: 120px){
.tabular-row, .tabular-cell { display: block; }
}
@media all and (min-width: 769px){
.tabular-row{ display: table-row; }
.tabular-cell { display: table-cell; }
}
-->
</style>

That's it!

Final note

Depending on your server, protocols may be picky when referencing data resources.

Back to top