Jquery Datatables uncaught reference error - javascript

I put it in the variable already but it still gives me an error and it says uncaught reference error oTable is not defined
<script type="text/javascript">
$(document).ready(function(){
$("#test").click(function(){
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function( result ) {
var oTable = $("#datatable").DataTable({
processing: true,
data: result,
columns: [
{data: 'id'},
{data: 'title'}
]
});
}
});
});
$("#reload").click(function(){
oTable.DataTable().ajax.reload();
});
});
</script>
here is my html
<table id="datatable">
<thead>
<tr>
<th>ID</th>
<th>TITLE</th>
</tr>
</thead>
</table>
please help me Thanks

Hope this will work for you
Use Datatable Method to Load ajax,
No need to Initiate again to reload Datatble use oTable.ajax.reload();
I changed oTable to Global variable
$(document).ready(function () {
$("#reload").click(function () {
oTable.ajax.reload();
});
$("#test").click(function () {
window.oTable = $('#datatable').DataTable({
"ajax": {
"url": "https://jsonplaceholder.typicode.com/posts",
"dataSrc": ""
},
"columns": [{
"data": "id"
},
{
"data": "title"
},
]
});
});
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type='text/javascript'>
</script>
</head>
<body>
<button id="reload">
reaload
</button>
<button id="test">
test
</button>
<div class="container">
<table id="datatable">
<tr>
<th>ID</th>
<th>TITLE</th>
</tr>
</thead>
</table>
</div>

your oTable variable definition was on onSuccess callback, so it can't call from outside of onSuccess callback scope

Related

Server side processing Jquery Datatables Sharepoint

I have a >50000 SharePoint Online document library list being rendered using the working code below. The page load time is close to 10-15 seconds.
I tried to implement server side processing to reduce page load times, but it made no difference:
"processing": true, "serverSide": true,
<!DOCTYPE html>
<html">
<head>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/jquery-3.5.1.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/moment.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/datetime-moment.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/jszip.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/pdfmake.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/vfs_fonts.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/buttons.print.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="<SPO_SITE>/SiteAssets/js/dataTables.searchBuilder.min.js"></script>
<link rel="stylesheet" type="text/css" href="<SPO_SITE>/SiteAssets/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="<SPO_SITE>/SiteAssets/css/dataTables.jqueryui.min.css">
<link rel="stylesheet" type="text/css" href="<SPO_SITE>/SiteAssets/css/buttons.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="<SPO_SITE>/SiteAssets/css/select.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="<SPO_SITE>/SiteAssets/css/searchBuilder.dataTables.min.css">
<script>
$(document).ready(function() {loadItems();});
function loadItems() {
var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
var oDataUrl = siteUrl + "/_api/web/lists/getbytitle('LIST_NAME')/items?$top=200000&$select=Created,ATA,EncodedAbsUrl";
$.ajax({
url: oDataUrl,
type: "GET",
dataType: "json",
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandler,
error: myErrHandler
});
}
function mySuccHandler(data) {
try {
$('#table_id').DataTable({
"pageLength": 100,
"dom": 'Bfrtip',
"buttons": [ {extend: 'searchBuilder', config: {columns: [0,1,2,3,4,5,6,7],},}, 'copy', 'csv', 'pdf', {extend: 'print',exportOptions: {columns: [ 0, 1, 2, 3, 4, 5, 6, 7 ]}} ],
"aaData": data.d.results,
"aaSorting": [[0, "desc"]],
"aoColumns": [
{
"mData": "Created"
},
{
"mData": "ATA"
},
{
"mData": "EncodedAbsUrl",
"mRender": function ( data, type, full )
{return 'View';}
}
]
});
} catch (e) {
alert(e.message);
}
}
function myErrHandler(data, errMessage) {
alert("Error: " + errMessage);
}
</script>
</head>
<body>
<div>
<table id="table_id" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Uploaded</th>
<th>ATA</th>
<th></th>
</tr>
</thead>
</table>
</div>
</body>
</html>
You have to set backend code because serverside means you have to handle Datatable rows on server on each action on client side (change page , filter , search , ...)
For more informations here : https://datatables.net/examples/data_sources/server_side

Jquery Dialog not loading in aspnet MVC

i want to be to display child records when i click a button . The data is displayed as a table.
I have created a partial view that will display the records.
I have created a controller action method to return the partial view.
I have also added javascript code on the main page/view to call and load the dialog .
Here is the code for the main page/view
#model IEnumerable<LearningApp.ViewModel.Requistion>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
#{
ViewBag.Title = "Index";
}
</head>
<body>
<h4>Requistion List</h4>
<hr />
<table class ="table table-bordered"cellpadding="0" cellspacing="0" id="RequestGrid">
<tr>
<th>Request #</th>
<th>Date Made</th>
<th>Employee Name</th>
<th>Purpose</th>
<th>Directorate</th>
<th>Station</th>
<th></th>
</tr>
#foreach (var r in Model)
{
<tr>
<td>#r.RequestID</td>
<td>#r.RequestDate</td>
<td>#r.EmployeeName</td>
<td>#r.Purpose</td>
<td>#r.Directorate</td>
<td>#r.Station</td>
<td> <button type="button"class="ids" value="View Details" data-id="#r.RequestID"> View Details</button></td>
</tr>
}
</table>
<div id="dialog" title="View Requistion Details" style="overflow: hidden;">
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("#dialog").dialog({
autoOpen: false,
width: 400,
modal: true
});
$('.ids').click(function () {
var requestid = $(this).data('id');
//alert("You clicked me...again" + requestid)
//var productId = $(this).data('id');
//alert(requestid)
$.ajax({
type: "POST",
url: "/tblRequistions/GetRequistionDetail",
data: '{RequestID: "' + requestid + '" }',
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$('#dialog').html(response);
$('#dialog').dialog('open');
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
</body>
</html>
Here is the controller method to return partial view.
[HttpPost]
public ActionResult GetRequistionDetail(int RequestID)
{
List<RequistionDetails> listofdetails = new List<RequistionDetails>();
listofdetails = r.getAllRequistionsDetails(RequestID);
return PartialView("_details",listofdetails);
}
If remove the portion of code below from the main view, and i run the page and i click on the button (view details) the ajax call to the controller is made and the correct parameter is passed.
$("#dialog").dialog({
autoOpen: false,
width: 400,
modal: true
});
If i leave it, nothing happens(ajax call not made).
I have tried to change autoOpen: True to see whether the dialog can open when the view loads, it does not load.
So i suspect the problem to be with the dialog.
Any reason why the dialog code is not working.?
Ronald
Take a look at this code:
$(function() {
function getDataById(u, n, tObj) {
if (n == undefined || isNaN(n)) {
return false;
}
var results = false;
console.log("AJAX, making request:", u, "ID:", n);
$.ajax({
type: "POST",
url: u,
data: {
RequestID: n
},
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function(r) {
results = r;
},
error: function(x, s, e) {
console.log("AJAX", s, e, x);
}
});
if (tObj != undefined) {
tObj.html(results);
}
return results;
}
$("#dialog").dialog({
autoOpen: false,
width: 400,
modal: true
});
$('.ids').click(function() {
var rHtml = getDataById("/tblRequistions/GetRequistionDetail", $(this).data('id'));
if (rHtml) {
$("#dialog").html(rHtml).dialog("open");
} else {
// Proof of Concept / Example Data
$("#dialog").html("**SAMPLE**<br />ID: 1, Date: 12/12/12, Name: Homer Simpson, Request: Donut, Director: Mr. Burns, Location: Plant").dialog("open");
}
});
});
<h4>Requistion List</h4>
<hr />
<table class="table table-bordered" cellpadding="0" cellspacing="0" id="RequestGrid">
<tr>
<th>Request #</th>
<th>Date Made</th>
<th>Employee Name</th>
<th>Purpose</th>
<th>Directorate</th>
<th>Station</th>
<th></th>
</tr>
<tr>
<td>1</td>
<td>12/12/12</td>
<td>Homer Simpson</td>
<td>Donut</td>
<td>Mr. Burns</td>
<td>Plant</td>
<td> <button type="button" class="ids" value="View Details" data-id="1"> View Details</button></td>
</tr>
</table>
<div id="dialog" title="View Requistion Details" style="overflow: hidden;">
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css" rel="stylesheet" type="text/css" />
I cannot test with AJAX. So I included Sample Data for the dialog as a proof of concept, yet the script does try to connect to AJAX and shows the error to console.
It's written to be used in a few ways. You can also do this:
getDataById("/tblRequistions/GetRequistionDetail", $(this).data('id'), $("#dialog"));
$("#dialog").dialog("open");
I don't advise this method. If the AJAX call is slow or details don't return, the dialog could open with no data.

Unable to display dynamic data into bootstrap table

I am getting some data from backend server and trying to put in the bootstrap table every 5 seconds. It is not able to display in table although I can clearly see the json object coming from backend in my console. I tried using refresh, load and append as well as first argument to bootstrapTable function but it is not helping. I want the new data to append to existing data when it comes from the backend in json format but the table is displaying as completely empty in the UI.
Javascript file
$(document).ready(function() {
getUpdates();
function getUpdates() {
$.ajax({
type: "GET",
contentType: "application/json",
url: "/getUpdates",
dataType: 'json',
cache: false,
timeout: 600000,
success: function (output) {
// var $table = $('#table');
$('#table1').bootstrapTable('refresh', {
data: output
});
console.log("SUCCESS : ", output); //this display correctly in console
},
error: function (e) {
var json = "<h4>Response:</h4><pre>"
+ e.responseText + "</pre>";
console.log("ERROR : ", e +"Response Text: "+ e.responseText);
// $("#btn-update").prop("disabled", false);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(getUpdates, 5000); // The interval set to 5 seconds
}
});
};
});
html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Updates through messaging</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="https://unpkg.com/bootstrap-table#1.14.2/dist/bootstrap-table.min.css">
<link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/>
</head>
<body>
<div class="container" style="min-height: 500px">
<div class="starter-template">
<h1>CDC Consumer Example </h1>
<div class="container">
<table id="table1" data-height="450">
<thead>
<tr>
<th data-field="id">Id</th>
<th data-field="oldValue">Old Value</th>
<th data-field="newValue">New Value</th>
<th data-field="tableName">Table Name</th>
<th data-field="columnName">Column Name</th>
<th data-field="timestamp">Timestamp</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<script type="text/javascript"src="webjars/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="javascript/entry.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/bootstrap-table#1.14.2/dist/bootstrap-table.min.js"></script>
</body>
</html>
from looking at that libraries documentation I don't think that's how the refresh method works.
try something like this
$(document).ready(function () {
$('#table1').bootstrapTable({
url: '/getUpdates',
onLoadSuccess(data) {
setTimeout(getUpdates, 5000)
}
})
function getUpdates() {
$('#table1').bootstrapTable('refresh')
};
});
you have to use load not refresh in $('#table1').bootstrapTable('refresh',{data: output}); and just give your new data as a second parameter, for better understand you can see my example below(it's load every 5 seconds):
var mydata = [
{ id: 6521761346336241,
columnName: "sys_role_cd1",
newValue: "PARTY1",
oldValue: "PART1",
tableName: "entries1",
timestamp: 15550157197331
}];
$('#table1').bootstrapTable({data: mydata});
window.setInterval(function(){
//you can call your ajax and reload your table here
$(function () {
mydata.push({
id: 6521761346336242,
columnName: "sys_role_cd2",
newValue: "PARTY2",
oldValue: "PART2",
tableName: "entries2",
timestamp: 15550157197332
});
$('#table1').bootstrapTable('load',mydata);
});
//console.log("data reload",mydata);
}, 5000);
// to stop this loop you can use `clearInterval()`
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.js"></script>
<div class="container" style="min-height: 500px">
<div class="starter-template">
<h1>CDC Consumer Example </h1>
<div class="container">
<table id="table1" data-height="450">
<thead>
<tr>
<th data-field="id">Id</th>
<th data-field="oldValue">Old Value</th>
<th data-field="newValue">New Value</th>
<th data-field="tableName">Table Name</th>
<th data-field="columnName">Column Name</th>
<th data-field="timestamp">Timestamp</th>
</tr>
</thead>
</table>
</div>
</div>
</div>

$(...).DataTable is not a function even after including the js before dataTable

I have been trying to integrate a table into my website which pulls data from my database into the table on the website.
I have read all the possible solutions on the internet and couldnt fix the issue yet.
I am putting my code below to have a look.
Please point out where I'm goiing wrong in it and what can i do for it to work.
Otherwise suggest me another option to go for the same function of loading data from the database into the tables inti the HTML site.
The declarations that i have used before the code.
<!--Import jQuery before export.js-->
<script type="text/javascript" src="//code.jquery.com/jquery.js"></script>
<script src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.js"></script>
<!--Data Table-->
<script type="text/javascript" src=" //cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src=" //cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>
<!--Export table buttons-->
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
<script type="text/javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.24/build/pdfmake.min.js" ></script>
<script type="text/javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.24/build/vfs_fonts.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/buttons/1.2.1/js/buttons.print.min.js"></script>
<!--Export table button CSS-->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.2.4/css/buttons.dataTables.min.css">
This is my HTML code.
<div style="width:90%; margin:0 auto;">
<table id="myTable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
</table>
</div>
This is my Javascript code.
<script>
$(document).ready(function () {
$('#myTable').DataTable({
"ajax": {
"url": "/api/medical_inventory/",
"type": "GET",
"datatype": "json"
},
"columns" : [
{ "data": "Id", "autoWidth": true },
{ "data": "Name", "autoWidth": true },
]
});
});
</script>
Any help is appreciated.
Thanks in advance.
You probably want to have the ajax call actually return data, and then pass that on to DataTable. As an example:
$.ajax({
url: "/api/medical_inventory/",
type: "GET",
datatype: "json",
success: function(data){
$("#myTable").DataTable({
data: data,
columns : [
{ title: "Id", className: "myClass" },
{ title: "Name", className: "otherClass" },
]
});
}
});

Unable to expand rows after destroy and reload; Cannot read property '_detailsShow' of undefined;

I am using the jQuery DataTable for creating a web page. I have a use case where the page opens with the table already populated. Now, there is a form in the page where he can put some filters and refresh the table. Also, more importantly for each row, I can expand to see more details as explained here.
In my case, as soon as the data is reloaded after the form is submit, the details button which would expand each data row stops working. It gives the following error:
jquery.dataTables.min.js:120 Uncaught TypeError: Cannot read property '_detailsShow' of undefined
I am reloading thee table by first clearing, destroying and then calling the DataTable method. Here's my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.1.2/css/select.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="../../../static/css/chosen/bootstrap-chosen.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../../../static/js/bootstrap/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.1.2/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.11/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(
function ()
{
var dashboard_table_id = "#example";
function destroy_existing_data_table()
{
var existing_table = $(dashboard_table_id).dataTable();
if (existing_table != undefined)
{
existing_table.fnClearTable();
existing_table.fnDestroy();
}
}
function create_dashboard_table()
{
var data_table = $(dashboard_table_id).DataTable({
"data": [{
"dt_RowId": 10,
"column1": "delhivery",
"column2": "CRP12345",
"column3": "1122",
"column4": "One expanded row"
}, {
"dt_RowId": 2,
"column1": "delhivery",
"column2": "CRP12345",
"column3": "1122",
"column4": "Other expanded row"
}],
"columns": [
{"className": "select-checkbox", orderable: false, "data": null, "defaultContent": ""},
{"class": "details-control", "orderable": false, "data": null, "defaultContent": ""},
{"data": "column1"},
{"data": "column2"},
{"data": "column3"}
],
"buttons": {},
"dom": 'lBfrtip',
"select": {
"style": 'multi',
"selector": 'td:first-child'
},
"oLanguage": {"sSearch": ""},
"order": [[2, 'asc']],
"bLengthChange": false,
"pageLength": 25
});
// adding event listener for opening and closing details
$(dashboard_table_id).find('tbody').on('click', 'tr td.details-control',
function ()
{
var tableRow = $(this).closest('tr');
var row = data_table.row(tableRow);
if (row.child.isShown())
{
tableRow.removeClass('details');
row.child.hide();
}
else
{
var rowData = row.data();
tableRow.addClass('details');
row.child("Hello there, this is the expanded view I am referring to....").show();
}
});
}
$("#example-form-submit").click(function (event)
{
event.preventDefault();
destroy_existing_data_table();
create_dashboard_table();
});
create_dashboard_table();
});
</script>
<style>td.details-control {
background: green;
cursor: pointer;
}
tr.details td.details-control {
background: blue;
}</style>
</head>
<body>
<div class="main-content lfloat">
<div class="container" style="width: 100%;">
<label for="example-form-submit" class="col-md-2 control-label"></label>
<div class="col-md-2">
<button type="submit" id="example-form-submit" class="btn btn-primary">Refresh and try to expand</button>
</div>
<div>
<table id="example" class="row-border hover order-column" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th></th>
<th>column1</th>
<th>column2</th>
<th>column3</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</body>
</html>
Can some one please point out what I am doing wrong. Thanks a ton in advance. This has been bugging me for some time now.
JSFiddle : Credits: #Edis Golubich
it works for me. just remove the latest click event handler by add .off before add the new one.
$(dashboard_table_id).find('tbody').off('click', 'tr td.details-control');
$(dashboard_table_id).find('tbody').on('click', 'tr td.details-control',function(){...});
The issue is that the data_table object is not getting 'updated' when using jQuery.on() via delegated event handling.
Try this: https://jsfiddle.net/f5mdcrup/4/
What I did was declare data_table outside of the function. The scope will be different in this case.
Following code works for me
$(dashboard_table_id).find('tbody').off('click', 'tr td.details-control');
$(dashboard_table_id).find('tbody').on('click', 'tr td.details-control',function(){
//Action To perform
});

Categories