Ajax requets for each page in pagination with datatables - javascript

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/

Related

Ajax Call to refresh web page

Update: I am using an apache server on the back-end and vanilla JS and jquery on the front-end.
Currently i have a web page that is displaying a variety of data that i am pulling from my back-end server.
How it works: I have a php script that is scraping directory names and displaying them in a dropdown. I have a refresh function set in my html for the web page that refreshes the page every 30 seconds.
The problem: I don't like the constant refresh, especially if there is nothing to update.
Is there a way to use ajax to pool my back-end server and check if new data has been entered in the directory and then update my dropdown?
Many thanks!
Use .data
window.setInterval(function() {
$.getJSON('/foo', { }, function(result) {
//Get the old data stored in the body using jquery data
var old_data = $('body').data('my_data');
//If objects are not the same, update cell
if ( ! equal_objects(result, old_data) )
update_cell();
//Store the new data
$('body').data('my_data',result);
});
}, 30000);
OBS: equal_objects is a function you should implement to compare 2 objects since JavaScript doesn't provide this functionality. See this post for details: Object comparison in JavaScript

Datatable client-side data change/redraw

I set up a datatables that initially gets from server some data and represents it, but then everything is left to the client. Some options are:
serverSide: false,
sAjaxSource: mySource,
My $.fn.DataTable.version is 1.10.2.
Then I need to change, client-side, the aaData under the table because some working on data is performed. I need to update the DT to show the client-altered temporary data without send another request to server (for two reason: prevent useless traffic and because that data is being altered).
I am looking for a way to edit the underlying DT databean to edit it, so then calling again
myTable.draw();
on my table I obtain a refresh realtime without sending another get to the server.
The question is, can I access DT data array, and can I edit it?
How is it done if is possible?
EDIT: I need to feed the table the full bean array as it initially took from the server, same format. So individual row/cell add/edit and client-side building functions are not suitable in my case, unless I manually cicle all objects.
SOLUTION
Use the code below:
// Retrieve data
var data = table.ajax.json();
// Modify data
$.each(data.data, function(){
this[0] = 'John Smith';
});
// Clear table
table.clear();
// Add updated data
table.rows.add(data.data);
// Redraw table
table.draw();
DEMO
See this jsFiddle for code and demonstration.

Simple pagination for jquery after ajax success of php select

I want to paginate the result of my ajax success. In my ajax when I get success I append all result into one table (this table is empty by default only header).
I used this tutorial but I can't figure out how to make it work when the table is empty by default. I was able to make it run when there are values by default.
When the table is populated after ajax success nothing is happening to the data all are displayed. Is there a more applicable sample or tutorial for this kind of scenario. Or what needs to be done on the current tutorial to make it work.
Any suggestion is appreciated
You shouldn't use pagination this way, I suggest you to make your function returning only the records needed for the selected page.
It's useles to make your ajax return all the set (ej. 300 rows) if you are only going to show only a subset (ej. 30 rows in page 1). So you should add to the function which return the records from the DB (lets call it getRecords) a few parameters more:
page: the current/selected page of the paginator
records: how many records you want to show in each page
Combining this two you can limit your sql accordingly, f.instance (you can prepare the limit and the offset before the call in your php code):
select blablabla from blablable where blablablu
limit records, offset (page * records)
note: the first page here is zero. So for the first page the first record will be 0 and the last record shown will be 30 (this is (0 + 1) *30).
Here you have a good tutorial.

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?

Multiple datatables per page

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 :)

Categories