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();
}
});
Related
I have made a filtering method. This method is working like a charm and when I type something the table updates to the search string. This is my method for the search:
loadList() {
var searchString = $(".search-input").val();
$.post('/Translation/List?searchString=' + searchString, function (data) {
$(".table-content-view").html(data);
});
}
And when I wanna insert a new record I call this method:
saveTranslation() {
$.ajax({
url: '/Translation/Edit',
data: new FormData($(`${tr.selectedclass} #translation-form`)[0]),
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
if (response.success === true) {
loadList();
}
}
});
}
This method works fine (confirmed with postman and chrome dev tools). The problem is I need to press F5 to see the new record instead that it refresh instantly. As you can see I call the method LoadList() to refresh the table but this doesn't work.
NOTE:
I use a partial view for the table.
This is my C# method for the list:
[HttpPost]
public async Task<IActionResult> List(string searchString)
{
var translations = _context.translation.AsQueryable();
translations = translations.OrderBy(x => x.CORETRANSLATIONID);
if (!String.IsNullOrEmpty(searchString))
{
translations = translations.Where(x => x.ORIGINAL.Contains(searchString));
}
return PartialView(await translations.ToListAsync());
}
Can someone point me in the right direction?
In my post method in JQuery I changed it too
saveTranslation() {
$.ajax({
url: '/Translation/Edit',
data: new FormData($(`${tr.selectedclass} #translation-form`)[0]),
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
loadList();
}
});
}
The if statement was not necessary.
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
}
},
});
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 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....
How to refresh the DataTable after changing in server side
Here i have define the dataTable when isData= 1 at server side mqsql(DB)
function one()
{
var DataTableApp = $('#DataTableApp').dataTable({
"sAjaxSource": "php/getAppDetails.php",
....
....
}
when click the some one in DataTable. I have changed isData=0, It is in ajax calling in another function.
After changing isData=0, I want to referesh the table..
How to referesh the DataTable
$.ajax({
type: "GET",
url: "php/removeApp.php",
data: data,
dataType: "json",
success: function (data) {
json_objApp = data;
if(json_objApp.isSuccessful == true)
{
document.getElementById('removeAppSucc').innerHTML = "Successfully Removed";
document.getElementById('collapseFive').setAttribute("class", "collapse");
DataTableApp.fnDraw();
DataTableApp._fnAjaxUpdate();
}
else
{
document.getElementById('removeAppSucc').innerHTML = "App is not removed"
}
},
});