im working on a databtable thats displaying data from my sql table. so far everything is displaying great however one of my fields needs to be able to be edited by the user and have that value updated in the database accordingly. I've been looking into multiple ways to do this but they havent been working. I've looked into form inputs,cell().edit() and onBlur from https://datatables.net but havent been able to get them to work. currently i have this for my script.
$(document).ready(function () {
var table = $('#example').DataTable({
serverSide: false,
language: {
searchBuilder: {
title: 'Custom Filter'
}
},
dom: 'Q<"pull-left"f><"pull-right"l>rtip',
ajax: {
url: "{{ url('/test') }}",
type: "GET",
datatype: "text",
data: {
q:"select * from exampleTable",
filename:"examplefile.json",
cacheInterval: 1
}
},
columns: [
{data: 'column1',title: 'column1'},
{data: 'column2',title: 'column2'},
{data: 'column3',title: 'column3'
"fnCreatedCell": function (nTd, oData) {
$(nTd).html("<input class='form-control' id='userInput' value='"+ oData.column3 +"'>");
}},
],
order: [
[0, 'asc']
],
column3 in this case would be the one that shows as form field showing the current data already filled as default but can be changed.
my html is in a separate blade with this.
<div class="card">
<div class="card-header">Test Table</div>
<div class="card-body">
<button class="updatebutton"type="submit">Submit</button>
<table id="example" class="table table-striped">
</table>
</div>
</div>
preferably It works like onBlur where they edit the line and as soon as they click off it updates the cell however I'll also take updating off the button click.
Related
On the list page user can edit info by click on Edit button and open details page for edit data.
After edit done return list page. This my source code
My JS listUser.js is embbed in jsp file at the bottom listusers.jsp
<div class="c-body">
<main class="c-main">
<div class="container-fluid">
<div class="fade-in" id="content">
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-sm-4">List Users</div>
<div class="col-sm-8 text-right">
<button id="create_user" type="button" class="btn btn-primary">Tạo mới</button>
</div>
</div>
</div>
<div class="card-body">
<table id="userTable" class="table table-striped table-bordered datatable">
<thead>
<tr>
<th>Username</th>
<th>Full Name</th>
<th>Site</th>
<th>Roles</th>
<th>Areas</th>
<th>Team</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script src="${contextPath}/user/listUser.js"></script>
</div>
</div>
</main>
</div>
listUser.js
$( document ).ready(function() {
var userTable = $('#userTable').DataTable( {
"processing": true,
"serverSide": true,
"pageLength": 10,
"ajax": {
"url": "/user/paginated",
"data": function ( data ) {
}},
"columns": [
{ "data": "username", "name" : "Username", "title" : "Username", "defaultContent" : ""},
{ "data": "full_name", "name" : "Full Name" , "title" : "Full Name", "defaultContent" : ""},
{ "data": "site_code", "name" : "Site" , "title" : "Site", "defaultContent" : ""},
{ "data": "user_roles", "name" : "Roles", "title" : "Roles", "defaultContent" : ""},
{ "data": "user_areas", "name" : "Areas", "title" : "Areas", "defaultContent" : ""},
{ "data": "team_code", "name" : "Team", "title" : "Team", "defaultContent" : ""},
{ "data": "status", "name" : "Status", "title" : "Status", "defaultContent" : ""},
{ "targets": "no-sort", "orderable": false, "data": "null", "name" : "Thao tác", "title" : "Thao tác", "defaultContent" : "<button id='updateUser' name='updateUser' class='btn btn-primary btn-edit' type='button' aria-pressed='true'>Sửa</button>"}
]
});
$('#userTable').on('click', '.btn-edit', function(){
var data = userTable.row( $(this).parents('tr') ).data();
//alert(data.user_id);
let url = "user/updateUser?id=" + data.user_id;
$("#content").load(url);
});
$(document).on('click', '#update_user', function(){
updateUser();
});
function updateUser() {
...
var data = {
...
};
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
if(myObj.status == "1"){
$("#content").load("user/list");
}
}
};
xhr.open("POST", "/user/update");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(json);
}
});
The problem I occurred DataTables warning: table id=userTable - Cannot reinitialise DataTable.
Thanks you.
From DataTable Docs (first result in search engine with the warning message you provided):
DataTables has a wide range of configuration options which can be used to customise the table at initialisation time, but only at initialisation time. After a DataTable has been initialised any attempt to use these options will result in an error.
Simply put, DataTables does not allow initialisation options to be altered at any time other than at initialisation time. Any manipulation of the table after initialisation must be done through the API [...]
You are not showing how you initialize DataTable, so I can't help you further, unless you update your answer with more information.
Edit
After gathering more info from you, I now can understand what you are trying to do.
Essentially: DataTables expects it's DOM elements to be managed by itself. Once you initialize a DataTable, you should not manipulate any DOM related to it. If you want to show something like the user editing page and go back to the table after save, you need to choose one of the next 2 options:
Completely unmount the DataTable before showing the user edit page and re-initialize it after saving user data and gathering new DataTable data from server.
Don't detach DataTable DOM: show user form in a modal, or hide the DataTable instead of removing it, and unhide it again after user data has been saved. Updated data will need to be reinjected into a living DataTables, which I think will need the use of the .ajax.data initialization option.
Depends on how much data is being transferred and processed I'd choose one or the other.
I have a data table for which I am doing an Axios get call and populating the tbody. As per observation, it is getting deformed (pagination not working, also if new data is just 10 rows, it shows 100 row. [Before update of 10 rows it was 100 rows so somehow data table not getting reinitialized])
This is my JavaScript which is updating tbody
<pre>
<script>
var sitename = "{{data.site.name | safe}}"
var avm = document.getElementById("ravm");
function loadAvm() {
axios.get('ravm', {
params: {
site: sitename
}
}).then(function (resp) {
console.log(resp.data.length);
avm.innerHTML = resp.data;
}).catch(function (err) {
console.log(err)
})
}
setInterval(function () {
loadAvm();
}, 3000);
</script>
</pre>
My Django template is below
{% for key, value in data.alerts.items%}
<tr>
<td class="text-{{value.severity}}">{{value.timestamp}}</td>
<td class="text-{{value.severity}}">{{value.message_text}}
</td>
</tr>
{% endfor %}
PS: Everything is working fine if I don't do this Axios call to update and just refresh pages to get new data from the view.
after a lot of research i was able to find my answer
table = $('#example1').dataTable();
oSettings = table.fnSettings();
table.fnClearTable(this);
table.DataTable().destroy();
table.find('tbody').append(resp.data);
table.DataTable({
"responsive": true,
"autoWidth": false,
"ordering": false,
"info": true,
"pageLength": 10,
"bDestroy": true,
"recordsFiltered": 10,
}).draw();
I have a little issue with my code. I want to display in console new data from update form but isn't working and I don't have any errors.
I have a list of items. When I click edit, I have an modal with current data and it's work fine. Issue comes when I try to display new data
data:
data(){
return {
advantage:{
icon: '',
title: '',
text: '',
},
advantages: [],
errors: [],
new_update_advantage: [],
uri: 'http://127.0.0.1:8000/api/advantages/'
}
},
Template
<div class="form-group">
<label for="icon">Icon</label>
<input v-model="advantage.icon" type="text" id="icon">
</div>
CreatModal2 works fine.
createModal2(index){
this.errors = [];
$( "#modal2" ).toggle();
this.new_update_advantage = this.advantages[index];
},
Issue comes here:
updateTask(){
console.log("TEST");
console.log(this.new_update_advantage.icon);
},
When I click the button, the console display only "Test" and don't show any errors
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/
So I have an app that shows expenses of a person. I made the view to add a new expense, but I don't know how to make the save button so it saves the expense in the db and redirects to the list of expenses.
The view has many fields like this:
<div id="selBxChSt" data-bind="dxLookup: {
dataSource: dsExpenses,
valueExpr: 'NAME',
displayExpr: 'NAME',
title: 'Expense',
searchEnabled: true,
value: selectedExpense
}">
</div>
And not only dxLookup, also dxTagBox,dxDateBox and dxTextArea.
I made the reset button, to set all fields to their default value. But I don't know how to save them to the firebird db.
This is the html for the button:
<div class="Column" data-bind="dxButton: {icon: 'todo', text: 'Save', type: 'normal', onClick: expenseSave}"></div>
So now I have to make a function in knockoutJS to save all the things the user chooses from the lookups.
I have no idea how to do this, I'm new to knockout.js and devexpress, so any idea or tips would be amazing, thank you!
To implement "old-school" form that submits data to a server-side go this way:
Wrap all editors and submit button with the form tag.
Use the useSubmitBehavior option for dxButton.
Set the name option for editors.
Your code should be like below:
<form action="your-action" method="post" data-bind="event: { submit: onFormSubmit }">
<div data-bind="dxTextBox: { name: 'login' }"></div>
<!-- other editors... -->
<div data-bind="dxButton: { text: 'Submit', useSubmitBehavior: true }"></div>
</form>
View model:
viewModel.onFormSubmit = function() {
// Here you can implement a custom logic before submit. Validate editors, for instance.
};
Refer this sample, as well.