Ajax override - using localStorage for the data source

This example shows how the ajax initialisation option can be used to replace the default Ajax call that Editor makes and instead use the browser's localStorage abilities to save the state of the table locally on the browser. This means that the user effectively has persistent storage, but it is available only to them on their current browser.

The code in this example shows the ajax option as a function that implements everything that is required by Editor for data storage and retrieval. The 'create', 'edit' and 'remove' actions are each handled by storing the submitted data in a local variable, which is then stored in local storage for data persistence.

Note that this example fully supports Editor's multi-row editing capability as it fully implements the client / server data interchange format Editor uses.

Although this particular use case is fairly limited, it does show how Editor's ajax option can be used to intercept and manage the data requests that Editor makes. Expanding on this almost any data storage system could be used from Firebase to WebSockets.

Item Status
Item Status
  • Javascript
  • HTML
  • CSS
  • Ajax
  • Server-side script
  • Comments (0)

The Javascript shown below is used to initialise the table shown in this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Object that will contain the local state
var todo = {};
 
// Create or update the todo localStorage entry
if (localStorage.getItem('todo')) {
    todo = JSON.parse(localStorage.getItem('todo'));
}
 
// Set up the editor
var editor = new DataTable.Editor({
    table: '#example',
    fields: [
        {
            label: 'Item:',
            name: 'item'
        },
        {
            label: 'Status:',
            name: 'status',
            type: 'radio',
            def: 'To do',
            options: ['To do', 'Done']
        }
    ],
    ajax: function (method, url, d, successCallback, errorCallback) {
        var output = { data: [] };
 
        if (d.action === 'create') {
            // Create new row(s), using the current time and loop index as
            // the row id
            var dateKey = +new Date();
 
            $.each(d.data, function (key, value) {
                var id = dateKey + '' + key;
 
                value.DT_RowId = id;
                todo[id] = value;
                output.data.push(value);
            });
        }
        else if (d.action === 'edit') {
            // Update each edited item with the data submitted
            $.each(d.data, function (id, value) {
                value.DT_RowId = id;
                $.extend(todo[id], value);
                output.data.push(todo[id]);
            });
        }
        else if (d.action === 'remove') {
            // Remove items from the object
            $.each(d.data, function (id) {
                delete todo[id];
            });
        }
 
        // Store the latest `todo` object for next reload
        localStorage.setItem('todo', JSON.stringify(todo));
 
        // Show Editor what has changed
        successCallback(output);
    }
});
 
// Initialise the DataTable
$('#example').DataTable({
    columns: [{ data: 'item' }, { data: 'status' }],
    data: $.map(todo, function (value, key) {
        return value;
    }),
    layout: {
        topStart: {
            buttons: [
                { extend: 'create', editor: editor },
                { extend: 'edit', editor: editor },
                { extend: 'remove', editor: editor }
            ]
        }
    },
    select: true
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Object that will contain the local state
let todo = {};
 
// Create or update the todo localStorage entry
if (localStorage.getItem('todo')) {
    todo = JSON.parse(localStorage.getItem('todo'));
}
 
// Set up the editor
const editor = new DataTable.Editor({
    table: '#example',
    fields: [
        {
            label: 'Item:',
            name: 'item'
        },
        {
            label: 'Status:',
            name: 'status',
            type: 'radio',
            def: 'To do',
            options: ['To do', 'Done']
        }
    ],
    ajax: function (method, url, d, successCallback, errorCallback) {
        let output = { data: [] };
 
        if (d.action === 'create') {
            // Create new row(s), using the current time and loop index as
            // the row id
            let dateKey = +new Date();
 
            for (const [key, value] of Object.entries(d.data)) {
                let id = dateKey + '' + key;
 
                value.DT_RowId = id;
                todo[id] = value;
                output.data.push(value);
            }
        }
        else if (d.action === 'edit') {
            // Update each edited item with the data submitted
            for (const [id, value] of Object.entries(d.data)) {
                value.DT_RowId = id;
                Object.assign(todo[id], value);
                output.data.push(todo[id]);
            }
        }
        else if (d.action === 'remove') {
            // Remove items from the object
            for (const id of Object.keys(d.data)) {
                delete todo[id];
            }
        }
 
        // Store the latest `todo` object for next reload
        localStorage.setItem('todo', JSON.stringify(todo));
 
        // Show Editor what has changed
        successCallback(output);
    }
});
 
// Initialise the DataTable
new DataTable('#example', {
    columns: [{ data: 'item' }, { data: 'status' }],
    data: Object.values(todo),
    layout: {
        topStart: {
            buttons: [
                { extend: 'create', editor: editor },
                { extend: 'edit', editor: editor },
                { extend: 'remove', editor: editor }
            ]
        }
    },
    select: true
});

In addition to the above code, the following Javascript library files are loaded for use in this example:

    The HTML shown below is the raw HTML table element, before it has been enhanced by DataTables:

    This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The additional CSS used is shown below:

    1
     

    The following CSS library files are loaded for use in this example to provide the styling of the table:

      This table loads data by Ajax. The latest data that has been loaded is shown below. This data will update automatically as any additional data is loaded.

      The script used to perform the server-side interaction for this demo is shown below. This server uses PHP, so the PHP script is shown, however our download packages include the equivalent script for other platforms, including .NET and Node.js. Server-side scripts can be written in any language, using the protocol described in the Editor documentation.

      No comments posted for this page yet. Be the first to contribute!

      Post new comment

      Contributions in the form of tips, code snippets and suggestions for the above material are very welcome. To post a comment, please use the form below. Text is formatted by Markdown.

      To post comments, please sign in to your DataTables account, or register:

      Any questions posted here will be deleted without being published.
      Please post questions in the Forums. Comments are moderated.

      Other examples