I'm making an AJAX call from jquery Datatables to populate a table. The AJAX call is being made and it returns valid JSON (validated with JSONlint). What happnes is that Datatables creates an empty table before the AJAX call completes and returns data.
I've put the JSON returned by the web service into a file and used that as the sAjaxSource and Datatables populates the table properly, so this is a problem with Datatables not waiting for the AJAX call to complete.
Datatables seems to know that there is some problem with their AJAX calls because the documentation they include showing how to populate a table from an AJAX calls just loads data from a file.
Has anyone gotten Datatables to work with a real AJAX call (not loading JSON from a file)? I'd appreciate any pointers to a Datatables example that works with a real AJAX call.
I can also switch to a different table library. I decided to use Datatables over Jtable but I may have to switch if Datatables doesn't support AJAX.
Here's my code. Feedback on it is appreciated.
<html>
<head>
<link rel="stylesheet" type="text/css"
href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
</head>
<body>
<table id="example">
<thead>
<tr>
<th>Serial Number</th>
<th>Sales Order</th>
<th>Part Number</th>
<th>Part Description</th>
<th>Shipped Date</th>
<th>Date Sold</th>
<th>Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript" charset="utf8"
src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script type="text/javascript" charset="utf8"
src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
$(function() {
$("#example").dataTable({
"bServerSide": true,
"sAjaxSource": "/mtprest/Product/productByStatus?status=awaiting",
"aoColumns": [{
"mData":"serialNumber"
},{
"mData": "sONumber"
},{
"mData": "partNumber"
},{
"mData": "desc"
},{
"mData":"shippedDate"
},{
"mData":"soldDate"
},{
"mData":"status"
}
]
});
});
</script>
</body>
</html>
Here's the JSON returned by the web service:
{"iTotalRecords":12,"iTotalDisplayRecords":0,"sEcho":"","aaData":[{"productId":47209009,"serialNumber":"0909090","sONumber":"dev35001484_","partNumber":"987654KP-GL","desc":"TEST MEC","shippedDate":null,"soldDate":null,"status":"Awaiting Validation"}, ...}
I had lots of problems when I tried using an AjaxSource. I ended up making the web service calls myself, and then passing the returned JSON data into the DataTable when I initialize it.
Your JSON says "iTotalDisplayRecords":0
I think it is correct that datatables does not show any row.
Have a look at
http://datatables.net/usage/server-side
//Try This
$("#example").dataTable({
"bServerSide": true,
"sAjaxSource": "/mtprest/Product/productByStatus?status=awaiting",
"columns": [{
"mData":"serialNumber"
},{
"data": "sONumber"
},{
"data": "partNumber"
}
],
"columnDef" :
{ "targets" : 0, //first row
"render" : function (data) {
return data
}
},
{ "targets" : 1, //second row
"render" : function (data) {
return data
}
},
{ "targets" : 2, //third row
"render" : function (data) {
return data
}
}
});
//Do it for the number of rows you need.
Related
I am using Datatables, Yadcf and Select2. I have an Error as soon as I click on any filter. The error is. The select2('close') method was called on an element that is not using Select2. Unable to get property 'close' of undefined or null reference. I have placed the select2 cdn above the yadcf cdn. I placed an example here. Watch the console. https://jsfiddle.net/Paul2167/zusvc4ra/
I am using filters that sit outside of the table. I only have 2 filters. If they are both of type select2 then there is no error. But if only 1 filter is set to use select2. Then the error occurs when clicking either filter.
This is the html snippet
<div>
<span id="external_filter_container1">
<!-- leave the wrapper contents empty -->
</span>
</div>
<div>
<span id="external_filter_container2">
<!-- leave the wrapper contents empty -->
</span>
</div>
<div>
<table class="mytable2 display table">
<tbody>
//table data...
</tbody>
</table>
</div>
My datatable init file is here:
var oTable;
jQuery( document ).ready( function($) {
'use strict';
// start datatable
oTable = $('.mytable2').DataTable( {
pageLength: 10,
searching: true
});
// end datatable
// start yadcf
yadcf.init(oTable,
[
{
column_number : 0,
filter_container_id: 'external_filter_container1',
filter_reset_button_text: false,
select_type: 'select2',
filter_default_label: 'First'
},
{
column_number : 1,
filter_container_id: 'external_filter_container2',
filter_reset_button_text: false,
//select_type: 'select2',
filter_default_label: 'Last'
}
]
);
// end yadcf
}); // end ready function
This is already fixed in version already fixed in 0.9.4.beta.12 which has not been released yet. github.com/vedmack/yadcf/issues/500
Hello
i am coding a web page of posts, where I'd like to add a tag system, something like stack overflow.
I have found many useful codes already made like Tag it by: aehlke.
The problem it´s that i want to use almost all the code by vuejs.org.
I am at laravel 5.3 framework and vuejs also using jquery.
Coul you please help me with the js to make a "separated by comma" tag that only can use the tags already in Tags table.
i used the example in vuejs.org to make made a searchbox that searches at a vue var and displays it at the bottom, i tought i coul use laravel variables to make the vuejs var and then search, but how could i make that each time a value its clicked on the table at bottom, the text fields updates with a tag inside.
<script type="text/x-template" id="grid-template">
<table>
<tbody>
<tr v-for="
entry in data
| filterBy filterKey
| orderBy sortKey sortOrders[sortKey]">
<td v-for="key in columns">
{{entry[key]}}
</td>
</tr>
</tbody>
</table>
</script>
<div id="demo">
<form id="search">
Search <input name="query" v-model="searchQuery">
</form>
<demo-grid
:data="gridData"
:columns="gridColumns"
:filter-key="searchQuery">
</demo-grid>
</div>
Vue.component('demo-grid', {
template: '#grid-template',
props: {
data: Array,
columns: Array,
filterKey: String
},
methods: {
sortBy: function (key) {
this.sortKey = key
this.sortOrders[key] = this.sortOrders[key] * -1
}
}
})
// bootstrap the demo
var demo = new Vue({
el: '#demo',
data: {
searchQuery: '',
gridColumns: ['tag'],
gridData: [
{ tag: 'Movies'},
{ tag: 'Tv Shows' },
{ tag: 'Books'},
{ tag: 'Comics' }
]
}
})
Help.
This isn't a "code-this-for-me"-site so if you want some help you need to post some code and someone might tell you what's wrong with it.
Anyhow, one of these JS libraries might be of interest to you:
https://select2.github.io/
http://selectize.github.io/selectize.js/
I don't know how to render datatable in view, here is the code in my controller.
public function getTable()
{
$tasks = Todo::select(array('todos.id','todos.task','todos.deadline','todos.status'));
return Datatables::of($tasks)->make();
}
Any help will be appreciated.
You need to create the datatable structure in your view and call the controller method with jQuery.
For example in your view you can set the following html:
<table id="tasks" class="table table-striped table-hover">
<thead>
<tr>
<th class="col-md-3">ID</th>
<th class="col-md-3">Task</th>
<th class="col-md-3">Deadline</th>
<th class="col-md-3">Status</th>
</tr>
</thead>
</table>
And then add the following jQuery that calls your controller action
<script type="text/javascript">
var oTable;
$(document).ready(function() {
oTable = $('#tasks').dataTable( {
"sPaginationType": "bootstrap",
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "{{ URL::to('tasks/getTable') }}"
});
});
</script>
You also need to reference the following files in your page
http://code.jquery.com/jquery-1.10.2.min.js
and
http://cdn.datatables.net/1.10.0/js/jquery.dataTables.js
and also add the Controller/getTable method to your routes file (in the example above I wrote it as tasks/getTable
If you need features like filters, sorting, etc., try Nayjest/Grids package for Laravel. If you need just simple table -- previous response is preferred.
I have a couple of questions related to dojo. Firstly I have an example I copied from online and ran it and it works perfectly. By the way I am working on a web application in visual studio 2010. It runs fine but my question is that I use the urls (version 1.5) from the ajax.googleapis.com and it works but as soon as I use the src="/folder/dojo.js.uncompressed.js" with the local copy (version 1.7.1) in my folder in my web app, it doesn't work. Any ideas about this.
The second question is using the datagrid example but instead of hard coding the values for the datagrid; I want to pass the results of a sql query from a database to the datagrid. Does anyone have ideas on this?
Here is code showing an attempt to use a locally stored file:
<title>The Simplest Dojo DataGrid Example of All Time</title>
<link rel="stylesheet" type="text/css"
href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/claro.css" />
<link rel="stylesheet" type="text/css"
href="/Styles/Grid.css" />
<link rel="stylesheet" type="text/css"
href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojox/grid/
resources/claroGrid.css" />
</head>
<body class="claro">
<div style="width: 600px; height: 200px">
<table id="billsGrid" dojoType="dojox.grid.DataGrid">
<thead>
<tr>
<th field="number">Number</th>
<th field="name">Name</th>
<th field="position">Position</th>
<th field="victories" width="180px">Super Bowl Victories</th>
</tr>
</thead>
</table>
</div>
<script type="text/javascript"
src="/Styles/dojo.js.uncompresses.js"
djConfig="parseOnLoad:true"></script>
<script type="text/javascript">
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileReadStore");
</script>
<script type="text/javascript">
dojo.ready(function () {
var theGreatestTeamOfAllTime = {
items: [{
"number": "12",
"name": "Jim Kelly",
"position": "QB",
"victories": "0"
},
{
"number": "34",
"name": "Thurman Thomas",
"position": "RB",
"victories": "0"
},
{
"number": "89",
"name": "Steve Tasker",
"position": "WR",
"victories": "0"
},
{
"number": "78",
"name": "Bruce Smith",
"position": "DE",
"victories": "0"
}
],
identifier: "number"
};
var dataStore =
new dojo.data.ItemFileReadStore(
{ data: theGreatestTeamOfAllTime }
);
var grid = dijit.byId("billsGrid");
grid.setStore(dataStore);
});
</script>
</body>
</html>
This does not work with jscript errors cropping up.
could not load dojox/grid/DataGrid.js
To make it work locally, examine your djConfig and the script includes for dojo to ensure paths are correct, especially the baseUrl
djConfig = {
parseOnLoad: true,
baseUrl: "../dojoroot/dojo/"
}
ALso make sure you are including the correct stylesheets (all includes and stylesheets must point to the same dojo version)
Examine the Net tab in firebug to see any errors in urls
regarding your second question, dojo has a concept of datastores - these are client (javascript) side holders of data. Your server-side can return the query result in JSON (preferred), XML or any other format.
The client (javascript/html) can use AJAX to fetch this data and render it in a datagrid.
dojo has fancy stores such as queryreadstore that supports paging/lazyloading
A good place to start is the nightly tests for dojo:
http://archive.dojotoolkit.org/nightly/dojotoolkit/dojox/grid/tests/
Here are the steps I follow:
1) download dojo toolkit from http://dojotoolkit.org/download/
2) install it with your application root. Typically, in my application root directory, I have a directory called dojoroot under which i untar dojo toolkit
3) in your html, head section make sure your css links are pointing to local dojoroot. FOr xample:
4) Make sure your djConfig is correctly set:
djConfig = {
parseOnLoad: true,
baseUrl: "../../../dojoroot/dojo/"
};
note that the baseUrl is important - it is the directory in which dojo.js is located
5) for the dojo.js src include, make sure the path is correct. for example:
If there are errors, your Net tab in firebug will show them - they are usually related to path issues
I am trying to run this server side example for jquery datatable, but it keeps on giving the JSON format error.
My jsp code looks like this -
<script>
$(document).ready(function () {
$("#companies").dataTable({
"bServerSide": true,
"sAjaxSource": "/dummySearchProposals",
"sPaginationType": "full_numbers",
"iDisplayLength":3,
"bJQueryUI": true,
});
});
</script>
<body id="dt_example">
<div id="container">
<div id="demo_jui">
<table id="companies" class="display">
<thead>
<tr>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
and the ajax listener's return object is created using this -
String[] data1 = {"1","a1","a2"};
String[] data2 = {"2","b1","b2"};
String[] data3 = {"3","c1","c2"};
JSONArray data = new JSONArray();
data.put(data1);
data.put(data3);
data.put(data2);
outputData.put("sEcho", queryString.get("sEcho"));
outputData.put("iTotalRecords", "99");
outputData.put("iTotalDisplayRecords", "3");
outputData.put("aaData", data);
Manually going to the ajax link, returns this -
{iTotalDisplayRecords=3, iTotalRecords=99, aaData=[["1","a1","a2"],["3","c1","c2"],["2","b1","b2"]], sEcho=1}
Can anyone please suggest, what I might be doing wrong here.
That doesn't look like json data that you're getting back from the call. Here is a simple example of a json formatted object.
JSON- name value pairs separated by colons, each pair separated by commas. I threw in array below for good measure.
{"xxx":1, "yyyyy": 2, "z": [1,2,3,4]}