Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display JSON data in jQuery DataTables via Ajax?

I've been trying to get my JSON data in jQuery DataTables component.

First I wrote a JavaScript and a view like the code shown below:

$.fn.dataTable.Editor({
    ajax: "http://localhost/example22/index.php?r=site/display",
    table: "#example",
    fields: [{
        label: "Name:",
        name: "name"
    }, {
        label: "Designation:",
        name: "designation"
    }, {
        label: "Address:",
        name: "address"
    }, {
        label: "Salary:",
        name: "salary"
    }]
});

$('#example').DataTable({
    lengthChange: false,
    ajax: "http://localhost/example22/index.php?r=site/display",
    columns: [{
        allk: "name"
    }, {
        allk: "designation"
    }, {
        allk: "address"
    }, {
        allk: "salary"
    }],
    select: true
});

and a view like

<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Designation</th>
                <th>Address</th>
                <th>Salary</th>
            </tr>
        </thead>
</table>

and the url that is provided contains the following JSON data respectively

{
    "allk": [
        {
            "name": "raju",
            "designation": "developer",
            "address": "he is from viswasapuram",
            "salary": "30000"
        },
        {
            "name": "bob",
            "designation": "designer",
            "address": "no idea",
            "salary": "100000"
        },
        {
            "name": "bob",
            "designation": "designer",
            "address": "no idea",
            "salary": "100000"
        },
        {
            "name": "suresh",
            "designation": "designer",
            "address": "fffswss",
            "salary": "1212"
        },
        {
            "name": "john",
            "designation": "designer",
            "address": "california",
            "salary": "3000000"
        },
        {
            "name": "suresh",
            "designation": "tester",
            "address": "he is from cheeran maanagar",
            "salary": "20000"
        }
    ]
}

Can someone help me on how to use DataTables with this application?

like image 588
Khader Avatar asked Sep 11 '15 20:09

Khader


1 Answers

SOLUTION

Use ajax.dataSrc option to specify property holding data in your JSON response.

For example:

$('#example').DataTable({
   // ... skipped other options ...
   ajax: {
       url: "http://localhost/example22/index.php?r=site/display",
       dataSrc: 'allk'
   },
   columns: [
       { data: "name"}, 
       { data: "designation"}, 
       { data: "address" }, 
       { data: "salary"}
   ]
});

DEMO

See this jsFiddle for code and demonstration.

like image 131
Gyrocode.com Avatar answered Oct 20 '22 20:10

Gyrocode.com