Getting an error "Is null or not an object" - javascript

I have the following code:
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>
<table class="table" id="table_id">
<thead>
<th data-dynatable-column="pt_name">Name</th>
<th data-dynatable-column="unit">Unit</th>
<th data-dynatable-column="room">Room</th>
<th data-dynatable-column="fin">FIN</th>
<th data-dynatable-column="line_type">Line Type</th>
<th data-dynatable-column="line_loc">Location</th>
<th data-dynatable-column="line_days">Est Days in Place</th>
<th data-dynatable-column="insert_date">Insertion Date</th>
<th data-dynatable-column="last_dsg_change">Last Dsg Change</th>
<th data-dynatable-column="hosp_insertion">Hospital Insert</th>
<th data-dynatable-column="reason">Reason</th>
</thead>
<tbody></tbody>
</table>
<script src="//cdnjs.cloudflare.com/ajax/libs/json2/20130526/json2.min.js"></script>
<script type="text/javascript" charset="utf8" src="js/jquery-1.11.1.min.js"></script>
<script src="libs/jquery-dynatable/jquery.dynatable.js"></script>
<script>
$(function(){
$.get("model/20_mp_cc_get_cvcs.json",function (data) {
$('#table_id').dynatable({
dataset: {
records: data.cvc_list.qual
}
});
})
});
</script>
</body>
</html>
and a portion of the 20_mp_cc_get_cvcs.json is:
{
"cvc_list": {
"cvc_cnt": 12,
"patient_cnt": 6,
"qual": [
{
"dg_id": 20627424964.0,
"enc_id": 82048822.0,
"fin": "700001703",
"hosp_insertion": "y",
"insert_date": "05/29/2014",
"insert_dt_tm": "/date(2014-05-29t00:00:00.000-04:00)/",
"last_dsg_change": "",
"line_days": 31,
"line_loc": "upper",
"line_type": "cvc",
"pers_id": 69935620.0,
"pt_name": "buildtest , domainone",
"reason": "",
"room": "1rmh",
"unit": "1rmh"
},
{
"dg_id": 20627428586.0,
"enc_id": 82048822.0,
"fin": "700001703",
"hosp_insertion": "n",
"insert_date": "05/21/2014",
"insert_dt_tm": "/date(2014-05-21t00:00:00.000-04:00)/",
"last_dsg_change": "",
"line_days": 39,
"line_loc": "rt., brachial",
"line_type": "picc",
"pers_id": 69935620.0,
"pt_name": "buildtest , domainone",
"reason": "",
"room": "1rmh",
"unit": "1rmh"
}
]
}
}
I keep getting an error that says cvc_list.qual is "null or not an object". This is not happening in all browsers. Just in our Citrix VM running IE10 with Document Mode IE7. What might I be doing wrong?

$.get might not gurantee a JSON parse, better to use the full version -
$(function(){
$.ajax({
url: "model/20_mp_cc_get_cvcs.json",
dataType: "json",
type: "get",
success: function(data){
$('#table_id').dynatable({
dataset: {
records: data.cvc_list.qual
}
});
}
});
});
There is also a JSON.parse method available in IE7, so you can also use that one to parse on your side. So you might do something like this -
$.get("model/20_mp_cc_get_cvcs.json",function (data) {
if (typeof data == "string"){
data = JSON.parse(data);
}
$('#table_id').dynatable({
dataset: {
records: data.cvc_list.qual
}
});
})

Use dataType attribute in your ajax call.
As per jQuery docs, by default its value is evaluated based on guess;
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String The type of data that you're expecting back from the
server. If none is specified, jQuery will try to infer it based on the
MIME type of the response (an XML MIME type will yield XML, in 1.4
JSON will yield a JavaScript object, in 1.4 script will execute the
script, and anything else will be returned as a string).
Specify dataType : json in your ajax call if you are expecting a json from server side.
Or alternatively you can use, jQuery.parseJson
Sol#1
$.get("model/20_mp_cc_get_cvcs.json",function (data) {
$('#table_id').dynatable({
dataset: {
records: data.cvc_list.qual
}
});
}, "json"); // Tell jQuery that you are expecting json.
Sol#2
$.get("model/20_mp_cc_get_cvcs.json", function (data) {
var json = jQuery.parseJSON(data); // parse it
$('#table_id').dynatable({
dataset: {
records: json.cvc_list.qual // use the json here
}
});
});

Related

Datatables - Why row() method can not get index value?

here is my code (and ajax data) to insert index column to table. But I don't know why console log don't see the index value. I tried searching solution but couldn't find it. Someone please help me, thanks you so much.
<!DOCTYPE html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.11.5/datatables.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" />
<script>
$(function () {
var table = $('#example').DataTable({
ajax: '../ajax/data/objects_salary.txt',
columns: [
{
"render": function (data, type, full, meta) {
return meta.row + 1;
}
},
{ data: 'name' },
{ data: 'position' },
{ data: 'office' },
{ data: 'extn' },
{ data: "start_date" },
{ data: "salary" }
]
});
$('#example tbody').on('click', 'tr', function () {
var data = table.row(this).data();
console.log(data);
});
});
</script>
</head>
<body>
<div class="container mt-4 bt-4">
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Index</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Progress</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
Console log output
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "320800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
}
That's because the meta.row index is NOT part of the ajax data for the table. table.data() shows only the data (i.e., what you set in the data key of columns[] initialization option.)
Indeed, meta.row is just an index you're rendering via the meta object that - according to the Docs - is:
An object that contains additional information about the cell being
requested. This object contains the following properties (...etc)
try this:
$('#example tbody').on('click', 'tr', function () {
const data = dt.row(this).data();
const index = dt.row(this).index() + 1;
const rowData = {...data, index};
console.log(rowData);
});
P.S. var is legacy Javascript, use const / let instead (unless you've really good reasons to use var)
I suggest changing the id to something else, ex. salary_id. if that doesn't work can you also upload your objects_salary.txt

extracting values from rows to use in a URL

I have generated a data table using the Datatables jquery plugin. The table is populated with JSON.
I want to extract cell values when I make a selection to use in a URL but I can't get it to work.
#I'm using django
import json
#my list
users = [[1,26,'John','Smith'],[2,33,'Dave','Johnson'],[1,22,'Aaron','Jones']]
#my json
user_json = json.dumps(users)
<table class="table table-striped- table-bordered table-hover table-checkable" id="user-table">
<thead>
<tr>
<th>Age</th>
<th>Record ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
</tr>
</thead>
</table>
<script type="text/javascript">
var userData = {{user_json|safe}};
</script>
var SourceHtml = function() {
var dataJSONArray = userData;
var initTable1 = function() {
var table = $('#user-table');
// begin table
table.DataTable({
responsive: true,
data: dataJSONArray,
columnDefs: [
{
targets: -1,
title: 'Actions',
orderable: false,
render: function(data, type, full, meta) {
//this is where I need help. I need for each a-tag to link to a django url pattern such as href="{% url 'users:select-user' id=id_value %}"
return '<i class="la la-edit"></i>';
},
},
],
});
};
return {
//main function to initiate the module
init: function() {
initTable1();
}
};
}();
jQuery(document).ready(function() {
SourceHtml.init();
});
I need a href link to a django url pattern such as href="{% url 'users:select-user' id=id_value %}" in each a tag. however, I can't get the values from the cells.
Datatables columns.render option can be used to access full data source of current row.
By using columns.render as function type, we can use third (3)
parameter to access another column index form same row of data
source.
var userData = [[1,26,'John','Smith'],[2,33,'Dave','Johnson'],[1,22,'Aaron','Jones']];
$('#example').dataTable( {
"columnDefs": [ {
"targets": -1,
"data": null,
"title": 'Actions',
"render": function ( data, type, row, meta ) {
return 'Download';
}
} ]
} );

jquery Datatables and css not rendering in mvc 4

I have a simple view page, trying to render jquery datable for my view in MVC4.
My view [Admin.cshtml]
<div style="width:90%; margin:0 auto;">
<table id="myTable">
<thead>
<tr>
<th>Practice Name</th>
<th>Practice Address</th>
<th>Practice Email</th>
<th>Practice Telephone</th>
<th>Created Date</th>
</tr>
</thead>
</table>
</div>
and my reference to css and js for jquery datatables are underneath the section:
<link type="text/css" href="//cdn.datatables.net/1.10.9/css/jQuery.dataTables.min.css" rel="stylesheet"/>
#section Scripts{
<script type="text/javascript" src="//cdn.datatables.net/1.10.9/js/jQuery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#myTable').dataTable({
"ajax": {
"url": "/Home/Admin",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Practice_Name", "autowidth": true },
{ "data": "Practice_Address", "autowidth": true },
{ "data": "Practice_Email", "autowidth": true },
{ "data": "Practice_Telephone", "autowidth": true },
{ "data": "Created_Date", "autowidth": true }
]
});
});
</script>
}
and in my Controller, i have a simple GET section:
public ActionResult Admin()
{
var data = db.Practices.ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}
But, when i run this application, i am getting my resultset like this
Where am i going wrong ?
Change your controller method name:
public ActionResult Admin() to public ActionResult GetAdminData()
Create another action method:
[Authorize]
public ActionResult Admin () => View();
Modify your JavaScript code:
"url": "/Home/Admin" to "url": "/Home/GetAdminData"
And update CDN links because they are too old:
https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css
https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js
Why is all of this needed?
When you navigate to /Home/Admin your return View (the Admin.cshtml)
Your view contains some custom JavaScript logic which will try to fetch a list of items from the database (your GetAdminData method)
GetAdminData returns JSON which can be used by DataTables in order to show your desired content on the page.

Datatables Not Loading Nested Objects Ajax

Trying to get my ajax to load into data tables. I want to load 2 tables from the same ajax call but I can't even get 1 to load first. Let's get some snippet action going...
$(function() {
$("#tablepress-1").DataTable({
ajax: {
url: '/api/?action=getStats',
dataSrc: 'data',
"deferRender": true
},
"columns": [{
"instances": "Strategy"
},
{
"instances": "Exchange"
},
{
"instances": "Trades"
},
{
"instances": "PL"
},
{
"instances": "Uptime"
}
]
})
})
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="tablepress-1" class="tablepress tablepress-id-1">
<caption style="caption-side:bottom;text-align:left;border:none;background:none;margin:0;padding:0;">Edit</caption>
<tbody>
<tr class="row-1">
<td class="column-1">Strategy</td>
<td class="column-2">Exchange</td>
<td class="column-3">Trades</td>
<td class="column-4">PL</td>
<td class="column-5">Uptime</td>
</tr>
</tbody>
</table>
Since stack snippets don't support ajax data, I'll paste it here:
{"success":true,"data":{"instances":[{"Strategy":"...","Exchange":"...","Trades":"...","PL":"...","Uptime":"..."}],"trades":[{"Open":"...","Strategy":"...","Exchange":"...","Direction":"...","Size":"...","PL":"...","Close":"...","ID":"..."}]},"meta":{"botOnline":true,"threadCount":0,"balance":0.0028}}
Right now I just have my script outputting ... for each field. What happens is that the table headings disappear and no data ever gets loaded into the table.
I tried setting up a fiddle with the data source but it's my first time trying to use the echo feature. Maybe someone else knows how to do that: https://jsfiddle.net/Trioxin/kjhtn7wm/6/
I can't imagine what's wrong here. I thought I specified the json format properly but it appears not.
Regarding cross domain AJAX sources in jsfiddles you can use http://myjson.com
Your "table headings" disappear because they are not table headings. They are just a <tbody> row that will be removed as soon DataTables get some data. Do this instead:
<thead>
<tr class="row-1">
<th class="column-1">Strategy</th>
<th class="column-2">Exchange</th>
<th class="column-3">Trades</th>
<th class="column-4">PL</th>
<th class="column-5">Uptime</th>
</tr>
</thead>
You must either pass an array of objects or point to the path of that array, like dataSrc: data.instances. You could also have dataSrc: function(data) { return data.data.instances }
You define which object property that should be mapped into which column through the data option like { data: "Strategy" }:
columns: [
{ data: "Strategy" },
{ data: "Exchange" },
{ data: "Trades" },
{ data: "PL" },
{ data: "Uptime" }
]
forked fiddle -> https://jsfiddle.net/hfc10sxt/

query.dataTables.min.js - Uncaught TypeError: Cannot read property 'length' of undefined

I am new at JSon and have been searching all over the internet but can't find out where is the error. Can you help me, please? The controller returns the object but nothing is displayed, and it comes out an error saying "Cannot read property 'length' of undefined"`.
This is my main template file:
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
<script src="~/scripts/jquery-1.9.1.js"></script>
<script src="~/scripts/bootstrap.min.js"></script>
<!-- Data table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.10/css/dataTables.bootstrap.min.css " />
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.10/js/dataTables.bootstrap.min.js" type="text/javascript"></script>
This is my table:
<table class="table table-bordered" id="tabela">
<thead>
<tr>
<th>Nome</th>
<th>Quantidade</th>
<th>Preco</th>
<th></th>
</tr>
</thead>
</table>
This is my JSon:
$('#tabela').DataTable({
"columnDefs": [
{ "width": "5%", "targets": [0] }, {
"className": "text-center custom-middle-align",
"targets": [0, 1, 2, 3]
},
],
"language": {
"processing": "<div class='overlay custom-loader-background'><i class='fa fa-cog fa-spin custom-loader-color'></i></div>"
},
"processing": true,
"serverSide": true,
"ajax": {
"url": "/produto/BuscarTodos",
"type": "POST",
"dataType": "JSON"
},
"columns": [{
"data": "Nome"
}, {
"data": "Preco"
}, {
"data": "Quantidade"
}, {
"data": "IdProduto"
}, ]
});
This is my controller:
public JsonResult BuscarTodos()
{
try
{
string dados = "";
// Initialization.
string search = Request.Form.GetValues("search[value]")[0];
string draw = Request.Form.GetValues("draw")[0];
string order = Request.Form.GetValues("order[0][column]")[0];
string orderDir = Request.Form.GetValues("order[0][dir]")[0];
int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
ProdutoConexao con = new ProdutoConexao();
List<Produto> lista = new List<Produto>();
lista = con.FindAll();
// Total record count.
int totalRecords = lista.Count;
if (!string.IsNullOrEmpty(search) && !string.IsNullOrWhiteSpace(search))
{
// Apply search
lista = lista.Where(p => p.Nome.ToLower().Contains(search.ToLower())).ToList();
}
// Sorting.
lista = this.SortByColumnWithOrder(order, orderDir, lista);
// Filter record count.
int recFilter = lista.Count;
// Apply pagination.
lista = lista.Skip(startRec).Take(pageSize).ToList();
// Loading drop down lists.
var result = this.Json(new
{
draw = Convert.ToInt32(draw),
recordsTotal = totalRecords,
recordsFiltered = recFilter,
data = lista
}, JsonRequestBehavior.AllowGet);
return Json(result);
}
catch (Exception ex)
{
return Json(ex);
}
}
private List<Produto> SortByColumnWithOrder(string order, string orderDir, List<Produto> data)
{
// Initialization.
List<Produto> lista = new List<Produto>();
try
{
// Sorting
switch (order)
{
case "0":
// Setting.
lista = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.Nome).ToList() : data.OrderBy(p => p.Nome).ToList();
break;
}
catch (Exception ex)
{
// info.
Console.Write(ex);
}
// info.
return lista;
}
Just to check that your datatable setup is up and correct I will suggest to create an empty table (no controller) just to make sure that you have everything setup correctly. If that works I'll add your controller and dynamic data.
Datatables REQUIRE a specific HTML table format if it can't find it then you'll get that error.
The simplest table you can check with is the following:
<table>
<thead>
<tr>
<th>header 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content 1</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Footer 1</td>
</tr>
</tfoot>
The footer is optional, everything else is required.
EDIT 1:
Take a look at the similar example they posted

Categories

Resources