Ajax response render to datatables column
Ajax response render to datatables column
I have this very basic table displaying companies:
<
table id="companies" class="table table-striped table-bordered" cellspacing="0" width="100%">
Company Name Business Field Area Related Items Subscription ends
I am using "datatables 1.10" and the following initialization script:
oTable = $('#companies').dataTable({ "processing": true, "serverSide": true, "ajax": { "url": "ajax/companies/get_companies.ajax.php" "type": "POST" }, "columns": [ { "bSearchable": true, "data": "company_name" }, { "bSearchable": true, "data": "company_field" }, { "bSearchable": true, "data": "company_area" }, //{ "bSearchable": true, "data": "relative_items" }, //displays id numbers from DB eg: (6, 32, 17, 24) but I dont want to display just ID numbers { // Here I convert the item ID's array to Item Names "bSearchable": true, "data": "relative_items", "mRender": function ( data ) { var trimResponse = "initialValue"; //Set and initially define the trimResponse variable $.ajax({ type: "POST", url: "companies/get_relative_items.php", data: "datastring="+data, success: function(resp){ trimResponse = $.trim(resp); console.log(trimResponse); //works! I can see the item names in console log } }) return trimResponse; //HOWEVER, datatables display the initial value of this variable and NOT the new one set by the above function } }, { "bSearchable": false, "data": "subscription_end" } ], "order": [[1, 'asc']] }); //alert(trimResponse); //if commented out, it also displays the initial value and not the one acquired by ajax
By reading the comments along the javascript, you may have already figured out that in the fourth column I want to display each company's related items (which are stored in another DB table).
I can display the ID numbers so far, but since ID numbers are not "human-friendly" I use ajax to return the id numbers array (eg: 2, 5, 3, 12) as the actual names that correspond with each item id (eg: Shirt, Trouser, Sock, Jacket).
But, although I can see the names array displayed correctly in the console, the datatables fourth column displays only the initial value of the variable "trimResponse" and NOT the new value that was given by ajax...
Any suggestions on how to display the ajax response in the datatables column? Thank you in advance.
PS: Same question has been posted to stackoverflow earlier: http://stackoverflow.com/questions/26950516/ajax-response-render-to-datatables-column
Answers
SOLVED: After some time of frustration, it turned out that the key to the solution was simply a different approach to the problem!
Instead of returning the "unformatted" data to the column and try to render it differently, what I did was to format the data in the server-side script and then "return" it to the table.
I have posted the full solution (as answer to my own question) in stackoverflow:
http://stackoverflow.com/questions/26950516/ajax-response-render-to-datatables-column