refresh (or redraw) one ROW from "datatables" component WITH inline editing - datatable

After days of searching I decided to ask experts :)
This is my problem :
I'm using datatables (from the excellent https://datatables.net) , combined with inline editing function that are NOT provided by https://datatables.net
Inline editing is working well but
I'm searching a method to recalculate some columns in the datatable component that are NOT on the DB (because this are calculated columns) :
Column A : 10 (manually edited if needed)
Column B : 15 (manually edited if needed)
Column C : SUM A + B
This is the Datatable script :
<script>
$(document).ready(function() {
var table =
$('#mytable1').DataTable( {
scrollCollapse: true,
paging: true,
dom: 'Bfrtip',
} );
} );
</script>
This is the inline editing script :
function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat right");
$.ajax({
url: "pb_update.php",
type: "POST", data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#bee2bc");
}
});
}
This is a part of my table :
.....
<td contenteditable="true" onBlur="saveToDatabase(this,'test','<?php echo $faq[$k]["id"]; ?>')" onClick="showEdit(this);"><?php echo $test; ?></td>
......
Help will be appreciated !!
Thanks a lot

Related

Using Datatables AltEditor requested unkown parameter

I'm having trouble with Datatable AltEditor when trying to update rows.
Btw, I'm using flask as back-end.
This is my setup:
First I'll show you what the datatable looks like
Html table:
<div id='contenidoBienvenida'>
<table class="dataTable table table-striped" id="example" style="width: 100%">
</table>
</div>
Flask Routes:
#app.route('/getProfesores') #This route sends the json data with all the teachers
def getProfesores():
if 'numEmpleado' in session:
try:
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM usuarios")
r = [dict((cur.description[i][0], value) # IF NULO hacer algo
for i, value in enumerate(row)) for row in cur.fetchall()]
if (len(r) == 0):
return "No hay profesores"
return json.dumps({'data': r})
except Exception as e:
print(str(e))
return redirect(url_for('home'))
#This route receives the desired data to be edited, saves changes and returns new data as JSON
#app.route('/editar/profesor/', methods=['GET'])
def editarProfesor():
if 'numEmpleado' in session:
try:
numEmpleado = request.args.get('NumEmpleado')
nombre = request.args.get('nombre')
password = request.args.get('password')
correo = request.args.get('correo')
tipoCuenta = request.args.get('tipoCuenta')
perfilCompletado = request.args.get('perfilCompletado')
cur = mysql.connection.cursor()
query = "UPDATE usuarios SET NumEmpleado = %s, nombre = %s, password = %s, correo = %s, tipoCuenta = %s, perfilCompletado = %s WHERE NumEmpleado = %s"
cur.execute(query, (numEmpleado,nombre,password,correo,tipoCuenta,perfilCompletado,numEmpleado))
mysql.connection.commit() #Execute the update sql
cur.execute( #Now it grabs the edited row
"SELECT * FROM usuarios WHERE usuarios.NumEmpleado=%s" %
numEmpleado)
r = cur.fetchone()
cur.close()
return json.dumps({'data': r}) #sends the edited row as JSON -- SUCCESS
except Exception as e:
return redirect(url_for('home'))
profesoresDatatable.js:
$(document).ready(function() {
var columnDefs = [{
data: "NumEmpleado",
title: "Número Empleado",
},
{
data: "nombre",
title: "Nombre"
},
{
data: "password",
title: "Password"
},
{
data: "correo",
title: "Mail"
},
{
data: "tipoCuenta",
title: "Tipo Cuenta"
},
{
data: "perfilCompletado",
title: "¿perfilCompletado?"
}];
var myTable;
// local URLs are not allowed
var url_ws_mock_get = './getProfesores'; #Flask route which fill the datatable
var url_ws_mock_ok = './mock_svc_ok.json'; #not used
myTable = $('#example').DataTable({
"sPaginationType": "full_numbers",
destroy: true,
responsive: true,
ajax: {
url : url_ws_mock_get, #Flask route to obtain json data
// our data is an array of objects, in the root node instead of /data node, so we need 'dataSrc' parameter
dataSrc : 'data'
},
columns: columnDefs,
dom: 'Bfrtip', // Needs button container
select: 'single',
responsive: true,
altEditor: true, // Enable altEditor
buttons: [{
text: 'Agregar',
name: 'add' // do not change name
},
{
extend: 'selected', // Bind to Selected row
text: 'Editar',
name: 'edit' // do not change name
},
{
extend: 'selected', // Bind to Selected row
text: 'Borrar',
name: 'delete' // do not change name
},
{
text: 'Refrescar',
name: 'refresh' // do not change name
}],
onAddRow: function(datatable, rowdata, success, error) {
$.ajax({
// a tipycal url would be / with type='PUT'
url: url_ws_mock_ok,
type: 'GET',
data: rowdata,
success: success,
error: error
});
},
onDeleteRow: function(datatable, rowdata, success, error) {
$.ajax({
// a tipycal url would be /{id} with type='DELETE'
url: url_ws_mock_ok,
type: 'GET',
data: rowdata,
success: success,
error: error
});
},
onEditRow: function(datatable, rowdata, success, error) {
$.ajax({
// a tipycal url would be /{id} with type='POST'
url: './editar/profesor/', #flask route which save changes and returns edited row as JSON
type: 'GET',
data: rowdata,
success: success,
error: error
});
}
});
});
In the following example I will change the password for the user named Arturo Casanova, from '123' to 'password'
When I have finished editing and I click on save changes I get a warning about requested unknown parameters.
When I close the warning I get the success message
But the edited row is not inserted correctly
If I click on the Refrescar button(refresh button),it then will appear on the datatable correctly
This is the current JSON obtained by Flask Route'/getProfesores')
This is the JSON response after editing the row, the one that now should appear on the datatable
This are the scripts I'm using
<!--SCRIPTS-->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript"
src="https://cdn.datatables.net/v/bs4/jszip-2.5.0/dt-1.10.18/b-1.5.6/b-colvis-1.5.6/b-flash-1.5.6/b-html5-1.5.6/r-2.2.2/sl-1.3.0/datatables.min.js"></script>
<script src="{{url_for('static', filename='js/dataTables.altEditor.free.js')}}"></script>
<script src="{{url_for('static', filename='js/profesoresDatatable.js')}}"></script>
Got it working
I changed the line 285 of dataTables.altEditor.free.js
that._editRowCallback(data,b,c,d,e); changed to that._editRowCallback(rowDataArray,b,c,d,e);
Complete section:
that.onEditRow(that,
rowDataArray,
function(data,b,c,d,e){ that._editRowCallback(rowDataArray,b,c,d,e); },
function(data){ that._errorCallback(data);
});
And now it doesn't show warnings and it refreshes as it should do
I know this was posted a while ago but I'll repsond as I had exactly the same problem, and also because I got in touch with the developers of the altEditor who responded below with a comment about the proposed fix.
The reason that the fix works is that it uses the JSON that the browser sent to the server, and it's valid JSON.
Without the proposed fix the editor uses the JSON returned by your server and I think you will find that this is where the problem is. As long as your server returns valid JSON with a key/value pair for each column in your table, it will work.
As an example, here's my table:
In the function called by onEditRow I create a string containing keys and values and then encode it to JSON and return it:
$row = '{"client_number": "1", "name": "Mark", "phone": "89797979", "link": "http://someserver.com"}';
echo json_encode($row);
With that code when I click the edit button on any row it will display the record from the table. When I click to close the edit dialog the row in the table will change to show that $row I returned. If you try that it should be enough to demonstrate that with valid JSON containing a value for each column, the editor works.
When I look in the browser to see what it received from the call to the server, it shows this:
And finally, here's the table after closing the edit dialog box. It shows that record I returned:
Obviously your server function will need to deal with the actual record clicked on and generate $row from that.
I know this is a bit old, but Mark's answer seems to be the correct one per the documentation on github.
AJAX Setup
The datatable accepts the following callback functions as arguments:
onAddRow(alteditor, rowdata, success, error)
onEditRow(alteditor, rowdata, success, error, originalrowdata)
onDeleteRow(alteditor, rowdata, success, error)
In the most common case, these function should call $.ajax as expected
by the webservice. The two functions success and error should be
passed as arguments to $.ajax.
Within the procedures onAddRow, onEditRow, onDeleteRow, you can access
datatable object using alteditor.s.dt.
Webservice must return the modified row in JSON format, because the
success() function expects this. Otherwise you have to write your own
success() callback (e.g. refreshing the whole table).
There needs to be a matching JSON response with the modified data to update the record natively

Codeigniter update table when sorting with jquery sortable

I just learn codeigniter, and I take an old project I did in php and convert it to CI. I used PDO before that and was easier for me to update things in the database. I have some problems now updating the list_order in my database.
This is my view
echo "<li id=".$row->list_id." class='list_container'>" . $row->listTitle; ?> test </li>
My js file which takes all the lists in the DOM and sends the value over to my controllers function
$(function() {
$('#sortable').sortable({
axis: 'y',
opacity: 0.7,
handle: 'span',
update: function(event, ui) {
var list_sortable = $(this).sortable('toArray').toString();
$.ajax({
url: "lists/update_order",
type: 'GET',
data: {list_order:list_sortable},
});
});
This is how my database is structured right now for the lists table
How should I tell my controller to update the order the of the lists ?

Use ajax to filtering data table in codeigniter

i'm using codeigniter to build my project. I want to make filter use select box with ajax, but i confused. when user choose values from select box, then i want the table just show data that contain select box values. Can anyone help me please...
<script>
function show_result()
{
if($('#selectbox').val()!='')
{
$.ajax({
type: "POST",
url:'<?php echo base_url()?>controller/controller_function',
data:'selectvalue='+$('#selectbox').val(),
cache: false,
beforeSend : function ()
{
$("#idAjaxLoader").css("display",'');
},
success: function (data) {
$("#idAjaxLoader").css("display",'none');
$('#table-div').html(data);
},
error: function(data){
//return false;
}
});
}
}
</script>
write query in controller's controller_function and then load view with table by your expected result

refresh the page with ajax on a social network website

I want to create a social network website. but there is a problem when the page refreshes the page with ajax. there I am using setInterval every 5 seconds. but by the time the page refreshes, textarea also comments on reloading. how to order textarea in the comments do not reload when the page refreshes?
please help me !
Can You put up your Code in order to understand your problem more Precisely.?
Use :
$.ajax({
url: '--URL of ajax Page--',
type: 'POST',
data: {},
success: function(data) {
$(document).ajaxStop(function() {
**window.location.reload();** // This reloads the Page in a faster way.
});
}
});
my code like this:
The page refreshes (_view.php)
<div class="status">
<?php echo ' <span style="color: #f83e07">#SIF# '.$data->idUser->short_name.'</span> : '.date("D, d M Y, H:m:s",strtotime($data->tgl_update)).'</br>'.CHtml::link(CHtml::image(Yii::app()->baseUrl.'/images/member/'.$data->idUser->foto,'',array("width"=>50,"height"=>50)), array('user/view', 'id'=>$data->id_user)).'</br>';
if($data->id_user == Yii::app()->user->id){
}
echo '</br><div class="isi">'.strip_tags($data->isi, "<h1><u><div><br><h2><h3><h4><h5><h6><img><hr><font><b>").'</div>'; ?>``
reload the index page (index.php)
function callAjax(){
$.fn.yiiListView.update('datalist', {
data: $(this).serialize(),
success: function(html){
$('.view').mouseout(function(e){
ref = setInterval(function(){callAjax();}, 5000);
});
$('.view').click(function(e){
clearInterval(ref);
});
},
}
);
}

Jquery Datatable processing message doesnt go away after deletion of row

This is the code...
var oTable;
var aData;
var row;
$(document).ready(function() {
$('#example tbody tr').live('click', function (event) {
$(oTable.fnSettings().aoData).each(function (){
$(this.nTr).removeClass('row_selected');
});
$(event.target.parentNode).addClass('row_selected');
aData = oTable.fnGetData(this); // get datarow
row = $(this).closest("tr").get(0);
});
/* Add a click handler for the delete row */
$('#delete').click( function() {
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>Test/DeleteData",
data: "id="+aData[0],
success: function(msg){
//oTable.fnDeleteRow(aData);
var anSelected = fnGetSelected( oTable );
oTable.fnDeleteRow( anSelected[0] );
oTable.fnDeleteRow(oTable.fnGetPosition(row));
}
});
} );
/* Init the table */
oTable = $('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "<?php echo base_url(); ?>Test/Listener",
"sPaginationType": "full_numbers",
"iDisplayLength": 1,
"bSortClasses": false,
"aoColumns": [ { "bVisible": false} , null, null ]
} );
} );
/* Get the rows which are currently selected */
function fnGetSelected( oTableLocal )
{
var aReturn = new Array();
var aTrs = oTableLocal.fnGetNodes();
for ( var i=0 ; i<aTrs.length ; i++ )
{
if ( $(aTrs[i]).hasClass('row_selected') )
{
aReturn.push( aTrs[i] );
}
}
return aReturn;
}
What is happening :-
The server side data gets deleted on clicking delete link.But the Datatable doesnt refresh after deleting a row on server.The usual "processing" message comes after deletion on server.It stays there.The UI row stays there highlighted with message "Processing" in the middle of the page
What i have observed is :-
1)The response of Ajax source after the delete url is called is this :-
{"sEcho":1,"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":[["11","PD101-DH1234","adsasd"]],"sColumns":"PartId,PartNumber,PartDescription"}
2)After using firebug,i observed no abnormalities.Both the delete and get source requests are executed perfectly with response OK.
3)I am using FireFox 4.1
4)I am using DataTables 1.8.1 build.
Now Question :-
What do I change in the above code so that the datatable UI row gets deleted and datatable refreshes to bring the remaining rows ???
Please help me on this. I am new to datatables. This problem isn't going away. I have tried everything ! Waiting for replies :)
Have you tried calling fnDraw() after deleting the row?
oTable.fnDraw();

Resources