Rectangle 27 1

The issue that I was missing is the fact that the RENDER function (whether in Column or ColumnDefs) can be called multiple times depending on the TYPE (sort, display, type). Within the RENDER function I needed to add logic that returns the value that I need for the given type that's being rendered. When I want the custom sort value (the Id, and not the custom image tag), make sure I have logic for rendering the SORT type (and I guess, where TYPE = 'type' too). Otherwise, render my custom IMG that I need. Easy, right?

Here's the new code that correctly handles the sorting and the display as I require. Check the type and do what you need to...

{
                     "targets": 1,
                     "render":
                         function (data, type, row) {
                             var element = "<img id='status_" + row["UserId"] + "' src='" + data["ImageUrl"] + "' title='" + data["Description"] + "";

                             if (type === "sort" || type === 'type') {
                                 return data["Id"];
                             }
                             else {
                                 if (data["Id"] == "2") // add in-process name
                                 {
                                     var userId = row["ProcessUserId"].trim();
                                     element = element + " by " + userId;
                                 }
                                 return element + "'/>";
                             }
                         },
                     "searchable": false,
                     "sortable": true,
                 },

c# - Sorting jquery DataTables on JSON object property - using Orthogo...

c# jquery sorting datatables
Rectangle 27 0

var json = {"data":"abc","name":"Diago","Age":23};
var output = [];
output.push("<table>");
$.each(json, function(k, v) {
            output.push("<tr><td>");
            output.push(k);
            output.push("</td><td>");
            output.push(v);    
            output.push("</td></tr>");
});
output.push("</table>");

console.log(output.join(""));
$(document).ready( function () {

  var json = {"data":"abc","name":"Diago","Age":23};
  var output = [];
  output.push("<table>");
  $.each(json, function(k, v) {
            output.push("<tr><td>");
            output.push(k);
            output.push("</td><td>");
            output.push(v);    
            output.push("</td></tr>");
  });
  output.push("</table>");

  $("#container").append(output.join(""));

  $("#container").find("table").dataTable();


});
<!DOCTYPE html>
<html>
    <head>
        <link href="//datatables.net/download/build/nightly/jquery.dataTables.css" rel="stylesheet" type="text/css" />

        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script src="//datatables.net/download/build/nightly/jquery.dataTables.js"></script>

        <meta charset=utf-8 />
        <title>DataTables - JS Bin</title>
    </head>
    <body>
        <div id="container">
        </div>
    </body>
</html>

I need solution with plugin Datables from datatables.net.

Yes I get what you are suggesting but I need native datatables solution like aoColumn options et. when provided ajax url.

.dataTable()

javascript - jquery DataTables: single Object json to rows with key as...

javascript jquery datatables jquery-datatables
Rectangle 27 0

$(document).ready(function() {
oTable = $('#example').dataTable( {
    "sAjaxSource": "source.php",
    "aaSorting": [],
    "aoColumns": [
        { "mDataProp" : "NameID",
          "bUseRendered" : false,
          "fnRender" : function(oObj) {
                       return oObj.aData["Name"];
                       }
        },
        { "mDataProp" : "Priority"},
        { "mDataProp" : "Action"}
        ]
    } );
} );

jquery - DataTables sort with mDataProp and fnRender from JSON - Stack...

jquery json sorting datatables
Rectangle 27 0

http://datatables.net/ this might help.. And also u can learn something also.....

JQuery Datatables Stuck "Loading data from server" with JSON in IE7, I...

jquery json internet-explorer datatables
Rectangle 27 0

In the end I couldn't get this to work without eval, which i want to avoid. My workaround was to encapsulate the fnRender functionality (where I was combining several columns into one column) into the server layer, so that the server combined the columns and there was therefore no need to use fnRender to combine them. Shame, but there you go.

jQuery datatables json initialisation invalid json - Stack Overflow

jquery json parsing datatable
Rectangle 27 0

also, u can load the table data through json which makes the html page render faster. another great feature of datatable is it supports client side searching, sorting. Pagination (client/server side) through ajax/html request.

What is the advantage of using jquery DataTables for large databases? ...

jquery datatable
Rectangle 27 0

The way you pass $aoColumn to your script is wrong. You should pass it as JSON instead -- and if the JSON is being transferred inside HTML, it needs to be properly HTML-encoded as well:

$aoColumn = array(null, null, null, array('bSortable' => false));
echo '<input ... value="' . htmlspecialchars(json_encode($aoColumn)).'">';

And turn it back into an object with $.parseJSON:

var aoColumn = $.parseJSON($('#aoColumn').val());

However, I 'm not sure why you want to bother with the hidden field at all. You can pass the configuration to JavaScript directly:

<?php $aoColumn = array(null, null, null, array('bSortable' => false)); ?>

<!-- later on.... -->
<script>
    var aoColumn = <?php echo json_encode($aoColumn); ?>;
</script>

Good answer, but is it not a completely different approach? What if Mausumi not is able / allowed to change the PHP-script?

@davidkonrad: Then they should say that there are specific restrictions in place. Although I doubt that is the case, since the question says "my code is like...".

right, but as you can see - some times all we want is just an answer, not a lecture

php - aoColumns of datatables are not working properly - Stack Overflo...

php jquery sorting datatables
Rectangle 27 0

sType
$('#example').dataTable( {
    "aoColumnDefs": [
        { "sType": "numeric" }
    ]
} );

Thank you. This worked but when I applied this sort functionality of this column has been stopped working. Can you please let me know how to add sort functionality to this numeric column. Thanks in advance

javascript - How to impose numerical sort with jQuery and dataTables? ...

javascript jquery datatables
Rectangle 27 0

function sendSearchAccountDetailsRequest(orgQueryReqJSONString){

$.ajax({
        type : 'POST',
        url : ctx+'/SearchController',
        data: orgQueryReqJSONString,
        contentType: 'application/json',                                                                            
        success : function(response) {                   
        //process JSON response here                
        var counter = 0;
        var tableDataHTML = '';

        $.each(response.organizationDetailsList, function(counter){
            var $curr = response.organizationDetailsList[counter].organizationDetails;
            tableDataHTML += '<tr id="searched-row-'+counter+'" class="js-result-tbl-tbody-tr">'+
                             '<td>'+$curr.organizationID+'</td>'+
                             '<td>'+$curr.organizationName+'</td>'+
                             '<td>'+$curr.parentOpCoName+'</td>'+
                             '<td>'+$curr.registeredEmailID+'</td>'+
                             '<td>'+$curr.registeredPhoneNo+'</td>'+
                             '</tr>';               
            });

        $('#search-results-table-tbody').empty();
        $('#search-results-table-tbody').append(tableDataHTML);
        initResultDataTable();
        },
        error : function(response) {                 
        //handle errors here
        alert('Error !!!'+response);            
        }
});}

.recalling initResultDataTable() is giving an alert that it can not be recalled. I had to play a trick to make it work. I removed the call from $(document).ready() and called it after successful ajax and made changes in html <tbody id="search-results-table-tbody"> <!-- remove below row and append data here --> <tr> <td colspan="5"> No data available in table. </td> </tr> </tbody>

You can apply $('#account-details-result-table').DataTable({ "order": [], "columnDefs": [ { "targets" : 'no-sort', "orderable": false, }] }); this code direct after successful ajax call instead of recalling a function.

problem will remain the same. I have reached to a solution. I used destroy() method before calling initResultDataTable() to destro DataTable instance so that i can be reinitialized. var table = $('#account-details-result-table').DataTable(); table.destroy();

html - search, sort and pagination of jQuery DataTables not working wi...

jquery html datatables
Rectangle 27 0

I have model for MVC pattern:
    [DataContract]
    public class TestViewModelResult : ServiceResult
    {
        [DataMember(Name = "prototypes")]
        public List<PrototypeResult> Prototypes { get; set; }
}

I change script for page:

<script type="text/javascript">
    var vm = null;
    $(function () {        
        vm = new TestViewModel();        
        ko.applyBindings(vm);
        $(document).ready(function () {
            $('#testtable').dataTable({
                "bServerSide": false,
                "sAjaxDataProp": "prototypes",
                "sAjaxSource": '@Url.Action("GetFiles", "Home")',                
                "aoColumns": [
                { "mData": "id" },
                { "mData": "createDate" }               
                ]               
            }); 
        });        
    });
After that work fine

c# - jQuery datatables plugin : Get json from server and displaying ta...

c# asp.net-mvc-4 jquery-datatables
Rectangle 27 0

Json Example:  {readData:[{"id":1,"name":"clearing House"}]       



dTable = $('#tbl').dataTable( {
    "bJQueryUI": true,
    "sPaginationType": "full_numbers",       
    "bProcessing": true,       
    "sAjaxSource": "Fn.php",  //your url      
    "sAjaxDataProp": "readData", //your json obj
        "aoColumns": [
                      { "mDataProp": "id", "bVisible":false },
                      { "sTitle":"Provider Name", "mDataProp": "name" }
                     ]                       
    });


 Hope this helps u...

how will i return the json object?? im using php on server side so do i have to echo readData?

Jquery DataTables Search box returns no results if data was added usin...

jquery datatables
Rectangle 27 0

I have been looking at the dataTables documentation and I think the problem is with your JSON.

this is the example they gave. count: isn't one of the listed parameters the datatable is expected. Let me know if changing the JSON to return "draw". "recordsTotal", "recordsFiltered", and "data" as the parameters works. As I am still learning DataTables myself.

{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
    [
        "Angelica",
        "Ramos",
        "System Architect",
        "London",
        "9th Oct 09",
        "$2,875"
    ],
    [
        "Ashton",
        "Cox",
        "Technical Author",
        "San Francisco",
        "12th Jan 09",
        "$4,800"
    ],
    ...
]
Imports System.Web.Script.Serialization

Public Class DataTableJsonModel
    Public Property draw As Integer
    Public Property start As Integer
    Public Property length As Integer
    Public Property search As SearchModel
    Public Property order As OrderModel()
    Public Property columns As ColumnModel()

    Class ColumnModel
        Public Property Data As String
        Public Property Name As String
        Public Property searchable As Boolean
        Public Property Orderable As Boolean
        Public Property Search As SearchModel
    End Class

    Class SearchModel
        Public Property value As String
        Public Property regex As Boolean
    End Class

    Class OrderModel
        Public Const asc As String = "asc"
        Public Const desc As String = "desc"

        Public Property column As Integer
        Public Property dir As String
    End Class
End Class

Public Class DataTableReturnModel
    Public Property draw As Integer
    Public Property data As Object
    Public Property recordsTotal As Integer
    Public Property recordsFiltered As Integer
    Public Property errorMessage As String
End Class

Public Class AWS
    Public Property instance_type As String
    Public Property id As String
    Public Property architecture As String
    Public Property account As String
    Public Property name As String

    Public Property block_devices As BlockDeviceModel()
    Public Property ebs_optimized As Boolean
    Public Property group_name As String
    Public Property hypervisor As String


    Class BlockDeviceModel
        Public Property delete_on_terminate As Boolean
        Public Property name As String
        Public Property status As String
        Public Property volume_id As String
    End Class
End Class
@Code
    ViewData("Title") = "AWSDataTables"
End Code


<script>
    $(document).ready(function () {
        var table = $('#ec2_table').DataTable({
            "serverSide": true,
            "ajax": { url: '/Home/ec2',
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                data: function (d) {
                    return JSON.stringify(d);
                },
            },
            "columns": [
        { "data": "id" },
        { "data": "name" },
        { "data": "architecture" },
        { "data": "instance_type" },

            ],
            "lengthMenu": [[10, 25, 50, 100, 1000], [10, 25, 50, 100, 1000]],
            dom: 'T<"clear">lfrtip',
            tableTools: {
                "sSwfPath": "/Scripts/media/js/DataTables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
            }
        });
    });

</script>

<h2>AWSDataTables</h2>

<table id="ec2_table" class="order-column display compact" cellspacing="0" width="98%">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Architecture</th>
            <th>InstType</th>
        </tr>
    </thead>
</table>
Function AWSDataTables() As ActionResult
    Return View()
End Function

<HttpPost()> _
Function ec2(d As DataTableJsonModel) As JsonResult
    Dim dataresults As IEnumerable(Of AWS) = GetAWSTestList()
    Dim filteredData As IEnumerable(Of AWS) = dataresults
    Dim output As New DataTableReturnModel()

    'sorting happens here
    If Not String.IsNullOrEmpty(d.Search.value) Then
        Dim s As String = d.search.value.ToLower
        'this will obviously change based on your class.
        filteredData = dataresults.Where(Function(x) x.id.ToLower.Contains(s) OrElse
                                             x.architecture.ToLower.Contains(s) OrElse
                                             x.name.ToLower.Contains(s))
    End If

    'Ordering happens here
    If Not IsNothing(d.order) AndAlso d.order.Length > 0 Then
        Dim orderM As DataTableJsonModel.OrderModel = d.order(0)
        If Not IsNothing(orderM) Then
            Dim sortDirection As String = orderM.dir
            Dim columnM As DataTableJsonModel.ColumnModel = d.columns.ElementAtOrDefault(orderM.column)
            If Not IsNothing(columnM) AndAlso Not String.IsNullOrEmpty(columnM.Data) AndAlso Not IsNothing(GetType(AWS).GetProperty(columnM.Data)) Then
                If sortDirection = DataTableJsonModel.OrderModel.asc Then
                    filteredData = filteredData.OrderBy(Function(x) GetType(AWS).GetProperty(columnM.Data).GetMethod.Invoke(x, {}))
                Else
                    filteredData = filteredData.OrderByDescending(Function(x) GetType(AWS).GetProperty(columnM.Data).GetMethod.Invoke(x, {}))
                End If
            End If
        End If
    End If

    output.data = filteredData.Skip(d.start).Take(d.length)
    output.recordsFiltered = filteredData.Count
    output.recordsTotal = dataresults.Count

    Return Json(output)
End Function

I have been working on this and it turns out. If you do serverside you have to implement the search, sorting and paging all on your own. I will update this answer once I have gotten every aspect done.

Jquery DataTables AJAX Default Sorting Not Working - Stack Overflow

jquery ajax json datatables datatables-1.10
Rectangle 27 0

If you are on >= jquery 1.7 I suggest changing your syntax on the "on" function:

$('parent_element_present_on_page_load').on('click', 'child_element_loaded_later', function...

Refer to the delegated events syntax explanation here: http://api.jquery.com/on/

This should fire on events bubbling up the table from dynamically loaded child elements.

ruby on rails - jQuery datatables loaded from JSON, row click event on...

jquery ruby-on-rails json datatables
Rectangle 27 0

That I know of you don't inject html. It is certainly not the intended way of using the plugin as it essentially defeats the purpose. It is saying 'no data' because you literally gave the plugin no data to store in a cache somewhere and be able to sort, paginate, etc. All you did was append the html to the table tag ( not the datatable ). If you use the built in ajax functionality of datatables you just return the data you want in the table as json ( or another format if you supply the parsing ) and datatables automatically converts it to both the dom objects for display AND jquery objects for sorting and such.

P.S. when you do use the ajax functionality of the plugin its actually wrapping your table in a bunch of divs and adding a number of elements to it so the header you are clicking on isn't technically all that 'tied' to your table you declared in html if that makes sense? It is tied to a cache of objects that datatables uses to render the table for you.

Datatables Jquery plugin not supporting injection? - Stack Overflow

jquery jquery-plugins datatables
Rectangle 27 0

Press F-12 on ie8+ and open the Script console. There may be an error you can't see.

JQuery Datatables Stuck "Loading data from server" with JSON in IE7, I...

jquery json internet-explorer datatables
Rectangle 27 0

Well if it is a server-side datatable, what you can do is edit a json just before it is passed like in the beginning of ssp.class.php in the new datatables (tell me if you are using the old one) NOTE: in the new datatables, it is an inbuilt function called formatter that does the same but you can use custom function like this

if ($j == 6) {
  if ($data[$i][$columns[$j]['db']] == 1) {
      $data[$i][$columns[$j]['db']] = '<label class="btn-danger disabled btn">Stopped</label>';
  } else {
      $data[$i][$columns[$j]['db']] = '<label class="btn-success disabled btn">Running</label>';
  }

here i am simply editing a 0 and 1 in my db to a Label Stopped and Running you can do something like parse_date and store a reformatted one

javascript - Jquery Datatables column rendering and sorting - Stack Ov...

javascript jquery ajax datatables jquery-datatables
Rectangle 27 0

Json Example:  {readData:[{"id":1,"name":"clearing House"}]       



dTable = $('#tbl').dataTable( {
    "bJQueryUI": true,
    "sPaginationType": "full_numbers",       
    "bProcessing": true,       
    "sAjaxSource": "Fn.php",  //your url      
    "sAjaxDataProp": "readData", //your json obj
        "aoColumns": [
                      { "mDataProp": "id", "bVisible":false },
                      { "sTitle":"Provider Name", "mDataProp": "name" }
                     ]                       
    });


 Hope this helps u...

how will i return the json object?? im using php on server side so do i have to echo readData?

Jquery DataTables Search box returns no results if data was added usin...

jquery datatables
Rectangle 27 0

The way you pass $aoColumn to your script is wrong. You should pass it as JSON instead -- and if the JSON is being transferred inside HTML, it needs to be properly HTML-encoded as well:

$aoColumn = array(null, null, null, array('bSortable' => false));
echo '<input ... value="' . htmlspecialchars(json_encode($aoColumn)).'">';

And turn it back into an object with $.parseJSON:

var aoColumn = $.parseJSON($('#aoColumn').val());

However, I 'm not sure why you want to bother with the hidden field at all. You can pass the configuration to JavaScript directly:

<?php $aoColumn = array(null, null, null, array('bSortable' => false)); ?>

<!-- later on.... -->
<script>
    var aoColumn = <?php echo json_encode($aoColumn); ?>;
</script>

Good answer, but is it not a completely different approach? What if Mausumi not is able / allowed to change the PHP-script?

@davidkonrad: Then they should say that there are specific restrictions in place. Although I doubt that is the case, since the question says "my code is like...".

right, but as you can see - some times all we want is just an answer, not a lecture

php - aoColumns of datatables are not working properly - Stack Overflo...

php jquery sorting datatables
Rectangle 27 0

I would suggest using underscore.js (http://documentcloud.github.com/underscore). You can easily achieve any sort of map/reduce/select you want. Here an example:

var people = [{"Name":"John","Age":"22"}, {"Name":"Jack","Age":"56"}, {"Name":"John","Age":"82"}, {"Name":"Jack","Age":"95"}];

var num_johns = _(people).select(function(obj){ 
    return obj.Name === 'John'}).length;

alert(num_johns); //alerts 2

You can even go a step further and factor out the select function with some currying http://www.dustindiaz.com/javascript-curry/ - depends on what your exact problem is.

thanks for the reply. However I am looking for a c# solution. I actually have a copy of my program thats fully functional with the correct results using client side code. Due to the amount of rprocessing however it has now become extremely slow and need an alternative solution in C#.

jquery - how to retrieve count of different object types from JSON str...

c# jquery datatables
Rectangle 27 0

I'm not sure what the issue is. I am going to show you how I did it and then you can modify it accordingly. My way has no fancy features like sorting, filtering, etc. My code is not yet 100% complete, I am also still experimenting with the jQuery datatables.

I have a datatable that displays all of my banks, it just displays the id and the name of the bank.

<table id="banks-datatable">
     <thead>
          <tr>
               <th>#</th>
               <th>Name</th>
          </tr>
     </thead>
     <tfoot>
          <tr>
               <th>#</th>
               <th>Name</th>
          </tr>
     </tfoot>
</table>
$(document).ready(function () {
     $('#banks-datatable').dataTable({
          "aoColumns": [
               { "mDataProp": [0], "sWidth": "15%" },
               { "mDataProp": [1], "sWidth": "85%" }
          ],
          "bAutoWidth": false,
          "bFilter": false,
          "bLengthChange": false,
          "bProcessing": true,
          "bServerSide": true,
          "bSort": false,
          "iDisplayLength": 50,
          "sAjaxSource": '@Url.Action("GetAllBanks")'
     });
});
public ActionResult List()
{
     return View();
}
public ActionResult GetAllBanks(DataTableParameterViewModel parameterViewModel)
{
     Check.Argument.IsNotNull(parameterViewModel, "parameterViewModel");

     IEnumerable<Bank> allBanks = bankRepository.FindAll();
     IEnumerable<Bank> filteredBanks = allBanks;

     var result =
          from bank in filteredBanks
          select new[]
          {
               u.Id.ToString(),
               u.Name
          };

     return Json(new
     {
          sEcho = parameterViewModel.sEcho,
          iTotalRecords = allBanks.Count(),
          iTotalDisplayRecords = filteredBanks.Count(),
          aaData = result
     },
     JsonRequestBehavior.AllowGet);
}
public class DataTableParameterViewModel
{
     public string sEcho { get; set; }

     public int iDisplayStart { get; set; }

     public int iDisplayLength { get; set; }
}

I hope this helps. If it does not help then try breaking down the data that you are sending to the datatable, try sending one column through at a time to see where the issue is.

Here is an article on Code Project that you can read, there are a couple in the series:

jquery - mvc3 datatables plugin and json - Stack Overflow

jquery asp.net-mvc-3 jquery-plugins