Multiple datatables per page - javascript

I have multiple data tables per page, ranging from 4 to 8 ish.
All the tables have different settings. All the data is gotten via sAjaxSource (a javascript array).
My question boils down to:
Solution 1)
Should I have one seperate URL for each table? This seems to work, but means a full page load takes a lot longer.
Solution 2)
Have one same link for all the tables (and have seperate array name), so its only 1 download.
My questions are as follows:
Is there any recommmended solution for multiple data tables per page, that's best practice in terms of 1 or multiple links to get the javascript arrays.
If you provide the same ajax link to multiple datatables the browser seems to download them once per table instead of 1 time for all tables. Is this per "design" or a fault in my code?
Side note: I have checked http://www.datatables.net/examples/basic_init/multiple_tables.html and search the documentation but did not learn anything about the above questions.

In the case you described above, I would not rely on browser cashing, instead I would get data with my own single Ajax request. Store it in a local variable and for different tables use 'aaData' option.
var mydata;
$.ready(function(){
$.get("source/file.php", function(data){
mydata = data;
$('#table1').dataTable({ "aaData": mydata[0] });
$('#table1').dataTable({ "aaData": mydata[1] });
}, 'json');
});
but in the end solution depends on your needs, maybe you'll need lots of data, maybe it ll require paging and would be better off with multiple 'source' files with differed loading options etc.

The fact that the browser download the file only the first time when you provide the same link is, I think, due to the browser caching capabilities and has nothing to do with DataTables or your code. The browser put the content in its cache the first time and then serves it from there.
You can use this fact to your advantage by using the sAjaxDataProp option. I'm thinking something along these lines :
$('#table1').dataTable( {
"sAjaxSource": "sources/data.txt",
"sAjaxDataProp": "table1"
} );
$('#table2').dataTable( {
"sAjaxSource": "sources/data.txt",
"sAjaxDataProp": "table2"
} );
[ ... ]
$('#tableN').dataTable( {
"sAjaxSource": "sources/data.txt",
"sAjaxDataProp": "tableN"
} );
This will tell DataTable to look for a specific javascript array in the loaded content. Obviously, the data.txt file must contain the declaration of each table.
If you want to be sure that the browser do only one request, you could also load the data by an other means, a jQuery AJAX function for example, and then initialize the DataTables with an javascript array :
$('#table1').dataTable( { "aaData": array1 } );
$('#table2').dataTable( { "aaData": array2 } );
$('#tableN').dataTable( { "aaData": arrayN } );
I hope this will help :)

Related

Datatable Invalid JSON response

I have a problem with Datatables.
Until now, everything worked like a charm, now, from reasons unknown to me, datatables stopped working on my app.
My datatable ajax call is returning:
DataTables warning: table id=section-list - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
My datatables init:
sections.find('table#section-list').dataTable({
"ajax": '/admin/page/get-section-list',
"columns": [
{"data": "SectionID"},
{"data": "SectionAlias"},
{"data": "Edit"},
{"data": "Delete"},
], aoColumnDefs: [
{
bSortable: false,
aTargets: [-1, -2, -3] // disable sorting on last three columns (icons)
}
]
});
and my page/get-section-list action
....
return new JsonModel(["data" => $sections]); // this is equivalent to echo json_encode() in basic php
I tested my JSON in Json Parser AND it is 100% ok and there is no previous output before this json.
Im using DataTables 1.10.3 with jQuery v1.10.2
I ran into a similar problem working with a data.json file and found the information from here very helpful. Specifically the recommendation to open chrome dev tools, click the network tab, and then try the request again so you can see it in the network timeline.
In my case it looked like the json file in my "ajax": '/path/to/data.json' was still being written to at the same time the reload request was trying to access the data. Adding a delay around the reload request to give data.json time to complete solved the issue:
setTimeout(
function() {
$('#tableid').DataTable().ajax.reload(null, false);
}, 125);
But its hard to know what the optimal delay setting should be. So instead of doing the settimeout() (which works btw), I changed how I was writing my data from nodejs asynchronous fs.writeFile() to the synchronous fs.writeFileSync() when writing to the file.
Every case will be a little different but if you know the data source normally returns valid json, you may want to inspect if that source is changing at the same time datatables is trying to access it.

How to get cookie value from jquery tablesorter, which stores sorting?

In JavaScript code of web application, the table sorter is defined by:
$("#my-table").tablesorter({
headers: {
1: {
sorter: false
}
},
widgets: ["saveSort"]
});
So when the page is refreshed the sorting of table is saved, but when browser is closed, the table backs to its original sorting. So what I want is to get how table is sorted and save it to database. Can someone suggest me how I can obtain the cookie(s), which stores how table is sorted?
Thanks
When the saveSort widget (demo) saves the information, it tests the browser for localStorage first, then if that isn't available, it falls back to saving the sort to a cookie. So, you can either use the function built into the widgets file like this:
var myTable = $('#table1')[0],
myLastSort = $.tablesorter.storage( myTable, 'tablesorter-savesort');
or if you are using Chrome, go to that page and press F12. now click on the resources tab and look under "Local Storage"
The value may look a bit confusing, but it's just a JSON format:
{
"/tablesorter/docs/example-widget-savesort.html": {
"0": {
"sortList": [ [0,0],[2,1] ]
},
"1": {
"sortList": [ [0,0] ]
}
}
}
And it is broken down as follows:
"/tablesorter/docs/example-widget-savesort.html" is the url of the web page
"0" or "1" would either be the table ID or the index of the table on the page
"sortList" contains the actual sort list value
So as you can see in the above data, it is saving sort information for two tables on one web page.
You could use jQuery to save a cookie with the sorted colum. The next time that page is loaded, use either jQuery or server-side logic to get the value of the cookie, and sort the appropriate column. This might be useful reading: Can jQuery read/write cookies to a browser?

Ajax requets for each page in pagination with datatables

I am using Datatables and filling the data using Ajax from server side. I don't want to pull whole data at once from server but need to fetch results for a single page and when user press on next or previous link, I want to make an ajax call and fetch results on the fly for that page only.
Is it possible with datatables?
What you need is proper initialization
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "scripts/server_processing.php"
} );
} );
For complete documentation and example have a look here
you can use jQuery paginate plugin. It will serve exactly your purpose.
this will
1. bring one page data at a time
2. you can set no. of records per page.
3. browse pages back and forward
4. sort records on basis of coulmns
it will look something like this
http://th3silverlining.com/2010/04/15/pajination-a-jquery-pagination-plugin/

Convert many GET values to AJAX functionality

I have built a calendar in php. It currently can be controlled by GET values ​​from the URL. Now I want the calendar to be managed and displayed using AJAX instead. So that the page not need to be reloaded.
How do I do this best with AJAX? More specifically, I wonder how I do with all GET values​​? There are quite a few. The only solution I find out is that each link in the calendar must have an onclick-statement to a great many attributes (the GET attributes)? Feels like the wrong way.
Please help me.
Edit: How should this code be changed to work out?
$('a.cal_update').bind("click", function ()
{
event.preventDefault();
update_url = $(this).attr("href");
$.ajax({
type : "GET"
, dataType : 'json'
, url : update_url
, async : false
, success : function(data)
{
$('#calendar').html(data.html);
}
});
return false;
});
Keep the existing links and forms, build on things that work
You have existing views of the data. Keep the same data but add additional views that provide it in a clean data format (such as JSON) instead of a document format (like HTML). Add a query string parameter or HTTP header that you use to decide which view to return.
Use a library (such as YUI 3, jQuery, etc) to bind event handlers to your existing links and forms to override the normal activation functionality and replace it with an Ajax call to the alternative view.
Use pushState to keep your URLs bookmarkable.
You can return a JSON string from the server and handle it with Ajax on the client side.

ExtJS: Multiple JsonStores from one AJAX call?

I have an ExtJS based application. When editing an object, an ExtJS window appears with a number of tabs. Three of these tabs have Ext GridPanels, each showing a different type of data. Currently each GridPanel has it's own JsonStore, meaning four total AJAX requests to the server -- one for the javascript to create the window, and one for each of the JsonStores. Is there any way all three JsonStores could read from one AJAX call? I can easily combine all the JSON data, each one currently has a different root property.
Edit: This is Ext 2.2, not Ext 3.
The javascript object created from the JSON response is available in yourStore.reader.jsonData when the store's load event is fired. For example:
yourStore.on('load', function(firstStore) {
var data = firstStore.reader.jsonData;
otherStore.loadData(data);
thirdStore.loadData(data);
}
EDIT:
To clarify, each store would need a separate root property (which you are already doing) so they'd each get the data intended.
{
"firstRoot": [...],
"secondRoot": [...],
"thirdRoot": [...]
}
You could get the JSON directly with an AjaxRequest, and then pass it to the loadData() method of each JSONStore.
You may be able to do this using Ext.Direct, where you can make multiple requests during a single connection.
Maybe HTTP caching can help you out. Combine your json data, make sure your JsonStores are using GET, and watch Firebug to be sure the 2nd and 3rd requests are not going to the server. You may need to set a far-future expires header in that json response, which may be no good if you expect that data to change often.
Another fantastic way is to use Ext.Data.Connection() as shown below :
var conn = new Ext.data.Connection();
conn.request({
url: '/myserver/allInOneAjaxCall',
method: 'POST',
params: {
// if you wish too
},
success: function(responseObj) {
var json = Ext.decode(responseObj.responseText);
yourStore1.loadData(json.dataForStore1);
yourStore2.loadData(json.dataForStore2);
},
failure: function(responseObj) {
var message = Ext.decode(responseObj.responseText).message;
alert(message);
}
});
It worked for me.

Categories