How to make ajax request to mongodb - javascript

I am building an app using Meteor. I am using the jquery datatables package - www.datatables.net to present my data/records. According to the documentation, I would connect the table to my MongoDB database by:
$('#example').DataTable( {
serverSide: true,
ajax: '/data-source'
});
The part I am unclear of is the 3rd line - Can someone help me understand how to make an ajax call to return data from my MongoDB database?? Here is more documentation on server-side processing for datatables:
https://datatables.net/manual/server-side
I have a collection named Products with the fields description, brand, price.

<table id="example">
<thead id="dataTable-header">
<tr>
<th>ID</th>
<th>NAME</th>
</tr>
</thead>
</table>
var dataTable = $('#example').DataTable({
"orderable": false,
'searching': true,
"paging": true,
language: {
processing: "<i class='fa fa-refresh fa-spin'></i>"
},
"processing": true,
"serverSide": true,
"ajax": urlData,
"columns":[
{
"orderable": false,
"class": "details-control",
"data": null,
"defaultContent": ""
},
{"orderable": false, "data": "name" }
],
"columnDefs": [{
"targets": 3,
"render": function (data, type, row) {
return '<a name="editAnchor" class="fa fa-ban"></a>';
},
"className": 'text-center'
}]
});
urlData is your json data with fields Id and Name.

Related

DataTables warning: table id=tbl_new- Ajax error after adding serverSide: true,

var table = $('#canidateregtable').DataTable();
table.destroy();
$('#canidateregtable').DataTable( {
serverSide: true,
"ajax": {
"url" : "getdata",
"dataSrc" : "",
},
});
This is my datatable and some column like
"columns": [
{"data": "user_id",}
]
Why this error can anyone help me and this is in live in server
Setting attribute of Datatable differs from version of datatable js you are using.
If you are using Datatable version of greater than 1.10.0 use below syntax.
$('#canidateregtable').DataTable({
"sAjaxSource": "/GetData", // Your url
"bServerSide": true,
"bSearchable": true,
"order": [[1, 'asc']],
"columns": [
// You can mention here all your columns you want to display
{
"data": "Name",
}
]
});
}

JavaScript incorrect sorting of data in the table HTML

The table has columns with dates and when I need to sort the data by date and I see that they are sorted incorrectly.
The same problem with another column, it contains information such as string
Columns:
string
date
app.py
software_data = []
software_data.append(software.app_id)
software_data.append(current_user.timezoned(software.workflow.started).\
strftime("%Y-%m-%d %H:%M")
result = {"data": software_data}
return jsonify(result)
list.html
{% block page_block_content %}
<table id="portfolio" class="portfolio table no-margin">
<thead>
<tr>
<th class="appid">{{ _("AppID") }}</th>
<th class="datetime started">{{ _("Started") }}</th>
</tr>
</thead>
<tbody></tbody>
</table>
{% endblock %}
list.js
$(function () {
var loaders = [];
var table = $("#portfolio").DataTable({
"ajax": {
"url": portfolio_data_url,
"type": "POST"
},
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"stateSave": true,
"responsive": 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"
}
],
"fnInitComplete": function(){
$("#portfolio").css("width", "100%");
}
})
});
I think the problem is in javascript because there is a similar table without a javascript in which the sorting is done correctly.
For the record, OP appears to be using the jQuery DataTables plugin.
You are just passing the wrong values into the order option. Try:
[[ $(".portfolio thead th").index($(".portfolio thead .started")), "desc" ]]
Or, a simpler:
[[ 1 /*Sort by column index-1 (column 2)*/, "desc" ]]

How to invoke ajax call in jQuery DataTable using ASP.NET MVC

I'm using jQuery DataTables 1.10.13 plugin for awhile now. I have stumbled upon this issue which is related with ajax data source for my html table.
jQuery DataTable initialization inside Files.cshtml
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var oTable = $("#tblFile").DataTable({
"iDisplayLength": 10,
"bServerSide": true,
"sAjaxSource": "#Url.Content("PlayListFilesAjaxHandler")" + "?playListId=" + getParameter(),
"bProcessing": true,
"bStateSave": true,
"aoColumns": [
{
"sName": "FileName",
"bSearchable": true,
"bSortable": true,
"sWidth": '25%'
},
{
"sName": "FilePath",
"bSearchable": true,
"bSortable": true,
"sWidth": '50%'
},
{
"sName": "Order",
"bSearchable": true,
"bSortable": true,
"sWidth": '10%'
},
{
"sName": "Action",
"bSearchable": false,
"bSortable": false,
"sWidth": '15%',
"render": function (data, type, full, meta) {
return '<a class="btn btn-primary deleteButton" href=\"FileDelete/' + full[3] + '\">Delete</a>';
}
}
]
});
});
I wondered if this is the correct way of calling ajax request with a parameter?
Because, the PlayListFilesAjaxHandler method is not triggered after Files action result is invoked.
"sAjaxSource": "#Url.Content("PlayListFilesAjaxHandler")" + "?playListId=" + getParameter(),
This is the Files action result method and parameters of PlayListFilesAjaxHandler inside the home controller class
[Authorize]
public ActionResult Files()
{
return View();
}
public ActionResult PlayListFilesAjaxHandler(string playListId, JQueryDataTableParamModel param)
{ ... }
This is the structure of html table
<table id="tblFile" class="table table-responsive">
<thead>
<tr>
<th>
File Name
</th>
<th>
File Path
</th>
<th>
Sequence
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody></tbody></table>
Any help is greatly appreciated.
if you didn't use api controller, try to return with json result.
public JsonResult PlayListFilesAjaxHandler(string playListId,JQueryDataTableParamModel param)
{
return Json(IEnumerable);
}

Datatable showing wrong page numbers

Following is the HTML code:
<table id="myTable" class="dTable1 contentList table table-bordered" style="z-index: 2; ">
<thead id="tableHeader">
<tr id="headerRow">
<th>Time</th>
<th>Event</th>
<th>Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I am initializing the table on popup open using below JavaScript code:
showHistory = function (contentID) {
debugger;
var auditRes;
//var oTable = $('#AuditListtable').dataTable();
//oTable.fnDestroy();
//alert("outside");
$('#AuditListtable').dataTable({
"sAjaxSource":SERVERURL?contentId=' + contentID,
"aoColumns": [
{ "mData": "AccessDate" },
{
"mData": "EventDescription",
"bSortable": false
},
{
"mData": "IPAddress",
"bSortable": false,
"mRender": function (data, type, row) {
debugger;
return '<td> <span title="' + data + '">Played By: ' + row.FirstName + ', IP Address: ' + data + '</span></td>';
}
}
],
"paging": true,
"sDom": '<"top"p<"clear">>rt',
"sPaginationType": "full_numbers",
"searching": false,
"bFilter": false,
"processing": true,
"bServerSide": true,
"order":true,
"sServerMethod": "POST",
"bAutoWidth": false,
"iDisplayLength": 8
});
$('#historyPopup').modal('show');
}
The data will be populated in pop up. Currently we are having total 9 records but pagination is showing as 5 pages. After clicking on another page, it displays previous record. Table is not refreshed.
You've enabled server-side processing with "bServerSide": true. Most likely your response is incorrect.
If you indeed want server-side processing, your response should be something like:
{
"sEcho": 1,
"iTotalRecords": 9,
"iTotalDisplayRecords": 9,
"aaData": [
// ... skipped ...
]
}
where sEcho should have the value of sEcho parameter from the request, iTotalRecords is number of all records before the filtering, and iTotalDisplayRecords is number of all records after the filtering.
See server-side processing for more information.

Ajax Error datatables.net/tn/7

I have a project created on PHP laravel, and I'm immplementig Ajax on all my options that have datatables, I was working fine but somehow my Ajax stop working and don't know why.
When I select and option on my web site with a Datatable shows the mesage:
Datatables warning: table id=example - Ajax error. For more
information aboute this error, please see http://datatables.net/tn/7
And don't show my content tables. When I select right click->inspect element show the mesage:
Failed to load resource: the server responded http://tienda.local.com/ajax/getJSONResultsForDT?table=tipos&primaryKey=id&…art=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1423606401783
Network
Request URL:http://tienda.local.com/ajax/getJSONResultsForDT?table=tipos&primaryKey=id&draw=1&columns%5B0%5D%5Bdata%5D=id&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=clave_tipo&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=nombre_tipo&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=created_at&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=true&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B4%5D%5Bdata%5D=&columns%5B4%5D%5Bname%5D=&columns%5B4%5D%5Bsearchable%5D=true&columns%5B4%5D%5Borderable%5D=false&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B5%5D%5Bdata%5D=&columns%5B5%5D%5Bname%5D=&columns%5B5%5D%5Bsearchable%5D=true&columns%5B5%5D%5Borderable%5D=false&columns%5B5%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B5%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=3&order%5B0%5D%5Bdir%5D=desc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1423606554946
I don't know what is that bug.
This is my code:
<script type="text/javascript">
$(function () {
oDtable = $('#example').dataTable({
"scrollY": 300,
"order": [3, 'desc'],
"processing": true,
"serverSide": true,
"dom": 'T<"clear">lfrtip',
"tableTools": {
"sSwfPath": "/swf/copy_csv_xls_pdf.swf",
"aButtons": ["copy", "xls", "csv", "print"]
},
"ajax": "/ajax/getJSONResultsForDT?table=tipos&primaryKey=id",
"columns": [
{"data": "id"},
{"data": "clave_tipo"},
{"data": "nombre_tipo"},
{"data": "created_at"},
{"data": null},
{"data": null}
],
"columnDefs": [
{
"targets": [0],
"visible": false
},
{
"targets": [4],
"orderable": false,
"data": null,
"render": function (data, type, full, meta) {
return '<a data-toggle="modal" class="btn btn-info" href="tipos/' + data.id + '/edit" data-target="#myModal">EDITAR</a>';
}
},
{
"targets": [5],
"orderable": false,
"data": null,
"render": function (data, type, full, meta) {
var urlFormated = ''+data.nombre_tipo+'';
var encodedUrl = encodeURIComponent(urlFormated);
return '<a data-toggle="modal" class="btn btn-danger" href="/delete?id=' + data.id + '&nombre=tipos&nombretipo='+encodedUrl+'" data-target="#myModalDestroy">ELIMINAR</a>';
}
}],
"bPaginate": true,
"sPaginationType": "full_numbers",
"language": {
"url": "assets/js/DataTables-1.10.0/lang/" + "<?php echo $lang; ?>" + ".lang"
}
});
});
</script>
HTML
<table id="example" class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>ID</th>
<th>CLAVE TIPO</th>
<th>NOMBRE TIPO</th>
<th>FECHA CREACION</th>
<th>EDITAR</th>
<th>ELIMINAR</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Any help will be grateful!

Categories