Integrate two requests into one Javascript - javascript

$("input[type='checkbox']").on("change",function(){
if($(this).is(":checked")){
$.ajax({
url: portfolio_data_url,
type: 'POST',
data: "id="+$(this).val(),
success:function(r){
// succcess call
}
})
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<div><input type="checkbox" value="0" checked>All</div>
<div><input type="checkbox" value="1">AppID</div>
<div><input type="checkbox" value="2">Vendor</div>
</form>
I have several checkboxes whose values are passed using a POST request. If one checkbox is selected, the value is passed to the POST request.
But I already have code that passes POST requests:
list.js
$(function () {
var table = $("#portfolio").DataTable({
"ajax": {
"url": portfolio_data_url,
"type": "POST"
},
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"stateSave": true,
"processing": true,
"serverSide": true,
"deferRender": true,
"language": datatables_language,
"order": [[ $(".portfolio thead th").index($(".portfolio thead .appid")), "desc" ]],
"columnDefs": [
{
"searchable": false,
"orderable": false,
"targets": "no-sort"
}
]
})
});
How can I integrate the code into the list.js for everything to go with one query.
Because now two different requests are sent which lead to incorrect output of information.

You can use .DataTable function to send checkboxes checked value in one request like below:
Try this:
$(function () {
var table = $("#portfolio").DataTable({
"ajax": {
"url": portfolio_data_url,
"type": "POST",
"data": function(d){
var ids = $('input:checkbox:checked').map(function(){
return this.value;
}).get();
d.ids = ids;
}
},
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"stateSave": true,
"processing": true,
"serverSide": true,
"deferRender": true,
"language": datatables_language,
"order": [[ $(".portfolio thead th").index($(".portfolio thead .appid")), "desc" ]],
"columnDefs": [
{
"searchable": false,
"orderable": false,
"targets": "no-sort"
}
]
})
});
In Datatable Using the data parameter as a function allows the additional data to send to server
Official Documentation
Note: You will get checked checkboxes value as an array, You can use .join(',') after .get() to send values as comma separated string to use directly in query
Also, when user check any checkbox then we can refresh datatable ajax to send updated checked checkboxes like below:
$("input[type='checkbox']").on("change",function(){
table.ajax.reload();
});

It looks like the ajax function youy want to re-use is of DataTable's.
It's not a good idea to use the ajax function which is used by some other plugin.
Here the Ajax call you want to Re-Use is used by the function DataTable. Instead of re-using that you can create a wrap-up function which makes ajax request.
Every-time if you want to make ajax request you can call that function with specified parameters.
Example :
function customAjax(url,data,method,success_message,fail_message){
$.ajax({
url:url,
data:data,
method:method,
success:function(response){
alert(success_message);
},
error:function(response){
alert(fail_message);
}
});
}
And call using :
customAjax("xyx.php","username=abc&password=ushfush","POST","Login Successfull","Something went wrong");

Related

Having a problem with jquery datatables proper pagination

Trying to work around problem with datatables pagination. The problem is:
I have some code to initialize Datatable in Laravel:
<script>
$(document).ready(function () {
$('.js-dataTable-full').DataTable({
ajax: {
"url": "{{ route('page.data') }}",
"type": "GET",
},
"autoWidth": false,
"serverSide": true,
"pageLength": 5,
"bSort": false,
"searching": true,
// "order": [[1, "desc"]],
"processing": true,
"paging": true,
"pagingType": 'full_numbers',
.......................................
Some text below
The data is loaded correctly, however there's still an issue with pagination.
As you see, the pagination links are not active and cannot be clicked, though text on the left clearly says that there are only 5 of 8 entries on the page.
In the json response total number of items is present:
No ideas by now, so any help would be appreciated.

Post Data in php using datatables javascript serverside

i am trying to create a filter function from my datatables, how can i post the value that i want coming from the javascript to php using the datatables function?
here is my sample code from my datatables
var oTable = $('#datatables').DataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": base_url + "link",
"fnServerParams": function (data) {
data.filter_start_date = $('#filter_start_date').val();
console.log(data);
},
dom: 'lBfrtip',
buttons: [
'excel'
],
"lengthMenu": [[10, 20, 50, 100, 300, -1], [10, 20, 50, 100, 300, "All"]],
"pagingType": "full_numbers",
"language": {
"paginate": {
"previous": 'Prev',
"next": 'Next',
}
},
"bAutoWidth": false,
"aaSorting": [[ 0, "desc" ]],
});
and the data.filter_start_date value is i want it to be post from my php. thank you in advance, i am just really stuck with this problem or am i just doing it wrong.
On php you will get a param filter_start_date which will be sent on every datatables ajax request. Just use it to filter your results.
And in javascript you can do something like this to reload the table
$('#filter_start_date').change(function() {
oTable.ajax.reload();
});
EDIT:
Here's exactly how I use it:
$('#table').DataTable({
//configs
ajax: {
url: baseUrl('/ajax/load-docs'),
type: 'post',
data: function(d) {
d.initial_date = $('#initial_date').val();
}
}
});
and in php
$date = $this->getParam('initial_date'); //getParam from Zend_Framework Controller
in your case you can use $_POST['filter_start_date']

Refresh datatable data

I am trying to refresh the data from my table, but I am not using ajax and that is why when I try to use table.ajax.reload() it is not working.
It gives me wrong json response since the way I am declaring my table is this:
var table = $('.table').DataTable( {
"data": global_data,
"scrollX": true,
"pagination": false,
"lengthChange": false,
"bPaginate": false,
"language": {
"url": "http://cdn.datatables.net/plug-ins/1.10.16/i18n/Spanish.json"
},
"order": [[ 2, "desc" ]],
});
So in another process I update the variable global_data, how to refresh the data?
Thanks
If you are using datatables you can destroy the data with the following line:
$ ('# mytable'). dataTable (). fnDestroy ();
and fill the table again with the data you want.
var table = $('.table').DataTable( {
"data": global_data,
"scrollX": true,
"pagination": false,
"lengthChange": false,
"bPaginate": false,
"language": {
"url": "http://cdn.datatables.net/plug-ins/1.10.16/i18n/Spanish.json"
},
"order": [[ 2, "desc" ]],
});

DataTable not showing pagination buttons and records info - JQuery

Using Datatable plugin for pagination, I can't get it to display pagination buttons and records information ("Showing X out of Y Records"). It is fetching the records correctly when I am selecting the page size from the drop down just above the table, but for some reason, it is not showing pagination buttons.
My guess is that it has to know the Total Record count of the table, and I am giving it that in the ""iTotalRecords": 10000" part, I have 1000 records in my table, but still it is of no use. What exactly am I missing here?
It is passing the start (page number) and length (page size) params correctly.
Below is my code,
$('#leadDetailTable').dataTable({
"processing": true,
"serverSide": true,
"info": true,
"stateSave": true,
"lengthMenu": [[10, 50, 100, 500], [10, 50, 100, 500]],
"iTotalRecords": 10000,
"iDisplayLength": 10,
"searching": false,
"scrollY": false,
"scrollX": false,
"ajax":{
type: 'POST',
url: '#Url.Action("SearchLeads", "ResourceManagement")',
data: args,
success: function (result) {
/* Do things with result */
},
}
});
Have you tried adding following parameters:
"bPaginate":true,
"sPaginationType":"full_numbers",
"bLengthChange": true,
"bInfo" : true
I had the same issue and it was because I returned the wrong recordsFiltered value from the server-side. Make sure that the recordsTotal value represents the number of records(rows) in the table and the recordsFiltered value represents the number of rows that should stay hidden of the total rows. DataTables uses this information to create the pagination buttons.
Add the below property
"pagingType": "full_numbers"
What is the response being returned by the ajax request? It should include the following:
{
data: <the array of row data>,
draw: <the same value the request had for its draw value>,
recordsTotal: <the total number of records>,
recordsFiltered: <the total number of records after filtering>
}
If you don't want it to say "filtered from x records", then count the records after filtering and set both recordsTotal and recordsFiltered to that value.

jquery data table and sorting columns

I'm using jquery data table to display large amounts of data inside grid. I implemented server side pagination but I'm struggling with sorting data server side.
Below is my datatable initialization, answer with query for sorting is not the subject here, I just need a way to pass information of which column is clicked to the controller, the one upon I will do the sorting.
('#myTable').dataTable({
"processing": true,
"serverSide": true,
"info": false,
"pageLength": 10,
"lengthChange": false,
"stateSave": false,
"bPaginate": true,
"bFilter": false,
"sPaginationType": "full_numbers",
"info": "Page _PAGE_ from _PAGES_",
"infoEmpty": "No data",
"oPaginate": {
"sFirst": "First",
"sPrevious": "Previous",
"sNext": "Next",
"sLast": "Last"
},
"ajax": {
"url": "#string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/MyController/GetData",
"type": "GET",
"data": function (d) {
.....
},
},
preDrawCallback: function (settings) {
...
},
drawCallback: function (settings) {
...
},
"columns": [
{ "data": "Id" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Age" }
],
"columnDefs": [
{
targets: [0],
orderable: false
},
{
render: function (data, type, row) {
...
}
],
"order": [[0, "desc"]]
});
public ActionResult GetData(){
var sortColumn = ...
...
}
You can bind the 'order' event like this:
$('#myTable').on( 'order.dt', function () {
var order = table.order();
var column_selected = order[0][0];
var order_way= order[0][1];
doStuff(column_selected ,order_way);
});
See it in plugin reference
By specifying "serverSide": true,, datatables will by default add information to the request which you need to use in your server-side code. If you look in the Firebug Network panel, you will be able to see the request with the querystring parameters. See here for the full list of parameters. Note that the link is to the v1.9 documentation, because that's what it looks like you're using.
So for sorting, you'd be interested in iSortCol_0 and sSortDir_0 which relate to the clicked column and the sort direction respectively.
In your controller method, you would access the parameters like this:
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
var sortColumnDir = Request["sSortDir_0"];
You then need to incorporate this, and the other parameters into your query.
Here is an article on using server-side datatables with MVC

Categories

Resources