I'm using jquery datatables with version 1.10.12. I'm using dropdown to filters rows in datatables. I have server endpoints which returns data in json form (thanks to yajrabox for laravel). My question is how can I load new data into my existing instance
Here is my code
var candidateDT = $("#candidates").DataTable({
processing: true,
serverSide: true,
ajax: '{!! url("/admin/candidates") !!}',
});
$(".filters").on('click', function(){
var url = '{{ url("admin/candidates/filters") }}';
var filterby = $(this).data('filter-by');
var value = $(this).val();
if(value !== ""){
$.ajax({
url:url,
data: {'filterby':filterby, 'value':value},
success: function(response) {
candidateDT.clear();
candidateDT.reload();
}
});
}
});
Where url is my endpoint for data source, and filters is my dropdown
Thanks in advance
There is with Ajax you can send more parameter to access from back-end. So you can try following way:
$("#candidates").DataTable({
processing: true,
serverSide: true,
ajax: {
url: '{!! url("/admin/candidates") !!}',
type: "get",
data: function(f) {
f.varname = $("#field").val(); //here place
}
},
});
Related
I initialized the DataTable in a variable:
var dataTable = $("#selector").DataTable({
processing: true,
serverSide: true,
ajax: $.fn.dataTable.pipeline({
dataType: "json",
url: "/path/ajaxurl",
data: {
"fruits": "apple",
"veggies": "banana",
},
dataSrc: "data"
}),
sPaginationType: "extStyle"
});
Now, somewhere in my script I have this checkbox that when changed will add a new data on the ajax above then initialize the draw():
$(document).on("change", "#add-some-liquors", function(e) {
// some validations here
// My attempt to add this data
dataTable.data({"drinks" : "coca-cola"});
// Draw the dataTables
dataTable.clearPipeline().draw();
});
Seems that dataTable.data({"drinks" : "coca-cola"}); does not add the drinks on the POST when I checked on the backend, I only get the apple & banana which is the two default initialized data. What am I missing?
According to the API .data method is only for retrieving. Try holding data in a variable, updating that object and then using it in .ajax method.
var items = {}
ajax: $.fn.dataTable.pipeline({
dataType: "json",
url: "/path/ajaxurl",
data: items,
Declare your data as a variable and add the drinks value later.
var data = {
"fruits": "apple",
"veggies": "banana",
};
console.log(data);
//On the click event
$('#chk').on('click', function() {
if ($(this).is(':checked')) {
data['drinks'] = 'coca-cola';
} else {
//When unchecking the option, set it's value to null
data['drinks'] = null;
//Or delete the property.
//delete data['drinks'];
}
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="chk" />
The ajax.data object can be initialized as a function. The function will be evaluated each time the data is fetched. In this example, the value of the global variable selectedDrink will be sent with the ajax request as the drinks field.
var selectedDrink = "";
var dataTable = $("#selector").DataTable({
processing: true,
serverSide: true,
ajax: $.fn.dataTable.pipeline({
dataType: "json",
url: "/path/ajaxurl",
data: function(d) {
d.fruits = "apple";
d.veggies = "banana";
d.drinks = selectedDrink;
},
dataSrc: "data"
}),
sPaginationType: "extStyle"
});
$(document).on("change", "#add-some-liquors", function(e) {
selectedDrink = "coca-cola";
// Draw the dataTables
dataTable.clearPipeline().draw();
});
Not only should this be a straightforward operation but I'm following the documentation as well. I have an ajax call that returns a json data set. I've cleared the table successfully but when the success method is called nothing happens. The console statement shows that data is being returned... however the table remains empty. Any idea why?
JS
$('#SortByCoverage').click(function () {
var table = $('#theTable').DataTable();
table.fnClearTable();
$.ajax({
url: '/Home/Question2',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
$("#thetable").dataTable({
"aaData": data,
"aoColumns": [
{title:"AdId"},
{title:"BrandId"},
{title:"BrandName"},
{title:"NumPages"},
{title:"Position"}
]
});
}
});
Server Side Code
public JsonResult Question2()
{
var ads = _client.GetAdDataByDateRange(new DateTime(2011, 1, 1), new DateTime(2011, 4, 1));
var json = ads.Where(x => x.Position.Equals("Cover") && x.NumPages >= (decimal)0.5).Select(x => new{
AdId = x.AdId,
BrandId = x.Brand.BrandId,
BrandName = x.Brand.BrandName,
NumPages = x.NumPages,
Position = x.Position
});
return Json(json, JsonRequestBehavior.AllowGet);
}
Sample Data (client side)
EDIT
As pointed out in the comments I misspelled the element name dataTable in the success callback. However, now I'm getting the following error:
Cannot reinitialise DataTable. To retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy
Do I really have to destroy the table, once it's clear, to reload the data?
I added the bRetrieve and bDestroy. This got rid of the error but still no new data loaded into the table.
$.ajax({
url: '#Url.Action("Question2", "Home")',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
$("#theTable").dataTable({
//"bRetrieve": true,
"bDestroy": true,
"aaData": data,
"aoColumns": [
{title:"AdId"},
{title:"BrandId"},
{title:"BrandName"},
{title:"NumPages"},
{title:"Position"}
]
});
}
});
I would make a little different, see how:
var theTable = $("#thetable").dataTable({
"aaData": [],
"aoColumns": [
{data:"AdId"},
{data:"BrandId"},
{data:"BrandName"},
{data:"NumPages"},
{data:"Position"}
]
}).DataTable();
$('#SortByCoverage').click(function () {
$.ajax({
url: '/Home/Question2',
type: 'GET',
dataType: 'json',
success: function (data) {
theTable.clear().draw();
table.rows.add(data)
.draw();
}
});
I have the following code on index page the script contains part of the code that will call the data from test page
<div class="leftbox" id="proddisplay">
</div>
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
From test.php i am getting json array that looks like this
[1,2,"text","text2"]
I want to display the json array data in a tabular form and display it inside the div. the view of table should be something like this (it will have some css of its own)
static text: 1
static text: 2
static text: text
static text: text2
static text will be given by me and remains the same throughout however the values of array would change. can anyone tell how i can do so
individually i can display the data from json, but here i also need to put json data in a table and then put that table within a div
First of all you need to encode the array in php before sending to frontend, use json_encode() and then decode it in the success function using JSON.parse() . After just run a loop throught the array.
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
var returneddata = JSON.parse(returndata);
var htmlData= '';
for(var i=0; i<returneddata.length; i++){
htmlData+= 'static text: '+returneddata[i]+' <br>';
}
$('#proddisplay').html(htmlData);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
I've a table which is filled with data and initialised like this.
$.ajax({
url: 'api/parent/child',
type: 'POST',
data: {
sessionId: sessionId
},
success: function(data, status){
if(status == 'success'){
// data will be xml String
xmlDoc = $.parseXML(data);
var $events = $(xmlDoc).find("Loans");
var thisTable;
thisTable = $("#loan-data").dataTable({
scrollX: true,
});
var eventChildren = $events.children("loan");
eventChildren.each(function(index, event){
var $event = $(event),
addData = [];
addData.push($event.children("loanNumber").text());
addData.push(formatData($event.children("loanAmount").text()));
addData.push($event.children("loanDuration").text());
var loanStatus = $event.children("loanStatus").children("loanStatus").text();
if(loanStatus == 'Pending'){
var dynamicdata = "<a id=\"editLoan\" href=\"#myModal\" data-id=\""+$event.children("id").text()+"\" data-loanamount=\""+$event.children("loanAmount").text()+"\" data-loanduration=\""+$event.children("loanDuration").text()+"\" data-toggle=\"modal\" class=\"editLoan\">"+"<button type=\"button\" id=\"editClick\" class=\"btn btn-info btn-xs\"><i class=\"fa fa-check\"></i> Edit</button></a>";
addData.push("<font color='orange'>"+loanStatus+"</font>");
addData.push(dynamicdata);
}else if (loanStatus == 'Some Other' || loanStatus == 'Some Other 2'){
addData.push("<font color='green'>"+loanStatus+"</font>");
addData.push("");
}else if(loanStatus == 'Some Other 3'){
addData.push("<font color='green'><b>"+loanStatus+"</b></font>");
addData.push("");
}else {
addData.push("<font color='Red'>"+loanStatus+"</font>");
addData.push("");
}
thisTable.fnAddData(addData);
});
$('#loan-data').dataTable();
$("#loading-gif-advanced").hide();
}
},
failue: function(data) {
}
});
Here the entire data for the table will be displayed. I would like to do pagination in this. I've followed the example in this link.
https://www.datatables.net/examples/data_sources/server_side.html
But it seems the data is directly given from the server to the dataTable's ajax source, also the pagination is handled itself coz of server side ajax source. But I've to modify the data to be displayed in my table before supplying to the table which is I've done in my current code. I've to do the same process but with pagination. I can't seem to find an example which explains pagination for my kind of requirement.
try this method.
which calls api internally
check the input parametrs at the server side and modify your api method to query and retun data based on that parameters.
Note: return json if possible, instead returning xml and parsing
$("#loan-data").dataTable({
"processing": true,
"serverSide": true,
"ajax": "api/parent/child",
"aoData": { sessionId: sessionId },
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
type: 'POST', // or 'GET'
url: sSource,
data: aoData,
success: function(data, status){
if(status == 'success'){
//conversion from xml to javascript array
// and the final object will lool like
//var newData = {
// "draw": 9,
// "recordsTotal": 57,
// "recordsFiltered": 57,
// "data": adddata //created from xml
//}
fnCallback(newData);
$("#loan-data").show();
}
}
});
}
});
I have seen several examples and can't seem to get the hang of passing more than one variable to mysql using jquery. Here is my situation:
I have a page with 2 cascading drop downs,( they work great using jquery to update second drop down based on the first drop down.)
when the first drop down is selected jquery updates the second drop down AND passes the customer id to a php script that creates a new record in the tblinvoice table (this also works great no problems.)
when the second drop down is selected I need to pass that value along with the invoice number to my php script so I can update the record with the instid.(this is the part that don't work)
If I only pass the instid and manually put the invoice number in the where clause of the query all works fine. If I omit the where clause all records are updated as expected. I need to know what I am doing wrong or what is missing.
I will try to post the code here
jquery code
$(document).ready(function() {
$("select#cust").change(function() {
var cust_id = $("select#cust option:selected").attr(
'value');
var test = $("#test").val();
var din = $("#idate").val();
$("#inst").html("");
if (cust_id.length > 0) {
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
$('#inst').html(
'<img src="loader.gif" alt="" width="24" height="24">'
);
},
success: function(html) {
$("#inst").html(html);
}
});
if (test == 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
},
success: function(html) {
$("#invoice").html(html);
$("#test").val(1);
var inum = $("#inv").val();
$("#invnum").val(din +
"-" + inum);
}
});
}
}
});
$("select#inst").change(function() {
var inst_id = $("select#inst option:selected").attr(
'value');
var custid = $("select#cust option:selected").attr(
'value');
var invid = # ("#inv").val()
if (inst_id.length > 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: {
inst_id: inst_id,
}
cache: false,
beforeSend: function() {
},
success: function() {
}
});
}
});
});
I have tried using data: {inst_id:inst_id,custid:custid,invid:invid,} (no update to the table like this)
I also tried data: "inst_id="+inst_id+"&custid="+custid+"&invid="+invid,(this also gives no results.)
Can someone PLEASE look at this jquery and see if I am making a simple error?
Try this format:
data: { inst_id: inst_id, custid: custid, invid: invid },
You can post a JSON object to the server so long as you serialize it and then let the server know the data type.
First you need to define your JSON object:
var postData = { inst_id: inst_id, custid: custid, invid: invid };
Then update your ajax to use the serialized version of that object and let the server know the data type:
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: JSON.stringify(postData),
contentType: "application/json",
..continue the rest of your ajax....