blog, Website Design

Combining Column Data in jQuery DataTables

In my continuing saga of building a hybrid mobile app using Cordova, once again I ran into a problem.


The app I’m developing is for car dealerships.  It was suggested that the dealership inventory display in the app.  Being a web developer I figured this is easy..  It proved to be a little more difficult than I expected.

Having used jQuery DataTables in the past this seemed like a good tool to use for displaying the inventory list.  I created my PHP file that queried the mySQL database, got the results, and output a JSON file.  Then the real issue began.  If I wanted to redirect the user to a webpage there would have been no problem.  But I didn’t want that.  We wanted to keep the user in the app and have it all look and work seamlessly.

To make the table look nice (especially given the limited screen on a cell phone) I wanted to combine the year, make and model fields into one table column.  No matter what I did nothing seemed to work.  I did Google searches that turned up many horrible and non-working answers (I again swore that I’m going to quit looking for answers on stackoverflow).

After a few hours of frustration I decided to change my PHP file on the server side.  Again I was stuck with some issues.  I didn’t want to make multiple requests to the database just to build the array I wanted to output as a json file, but that seemed like my only solution.

At this point my brain must have assimilated enough information to slap me with an insight.  I did another search that took me to the mData reference for datatables.  I often find the help files very confusing and this was also the case with mData.


Enough of the story . . . here’s the working jQuery call to the php file that worked:

  $('#invTable').DataTable( {
      "ajax": "json-encode.php",
	  "columns": [
	    { "data":"VehicleType" },
            // use mData to combine json values
	    { "mData": function vehicle(data, type, dataToSet) {
		    return data.VehicleYear + " " + data.Make + " " + data.Model;
	    { "data": "MSRP" },
	    { "data": "StockNumber" }