Datatable not cleared usage - php

I am creating a simple report in PHP and AJAX displayed on Datatable.
The user shall be able to select the from date and to date, then data will be display according to the selected dates.
My problem is if I select no sales dates, the data are not cleared and still show the previous records, I don't understand why.
I attached the screenshot of the form below
I tried to achieve this with the code below
function get_all()
{
var total=0;
var amount=0;
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
$('#tbl-projects').dataTable().fnDestroy();
$.ajax({
url:"all_sales.php",
type: "POST",
dataType: 'JSON',
data:{from_date:from_date, to_date:to_date},
success: function (data)
{
$('#tbl-projects').dataTable({
dom: 'Bfrtip',
buttons: [
, 'excel', 'pdf', 'print'
],
"aaData": data
,
"scrollX": true,
"aoColumns": [
{"sTitle": "Member No", "mData": "mno"},
{"sTitle": "Member Name", "mData": "pname"},
{"sTitle": "Amount", "mData": "amount"},
{"sTitle": "Month", "mData": "months"},
{"sTitle": "Payment Date", "mData": "paydate"},
]
});
data.forEach(function(recordInLoop)
{
amount += Number(recordInLoop.amount);
});
$('#amount').val(amount);
},
error: function (xhr) {
console.log('Request Status: ' + xhr.status );
console.log('Status Text: ' + xhr.statusText );
console.log(xhr.responseText);
var text = $($.parseHTML(xhr.responseText)).filter('.trace-message').text();
console.log(text)
}
});
}

function get_all()
{
var total=0;
var amount=0;
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
$('#tbl-projects').dataTable().fnDestroy();
$.ajax({
url:"all_sales.php",
type: "POST",
dataType: 'JSON',
data:{from_date:from_date, to_date:to_date},
success: function (data)
{
$('#tbl-projects').dataTable({
dom: 'Bfrtip',
buttons: [
, 'excel', 'pdf', 'print'
],
"aaData": data
,
"scrollX": true,
"aoColumns": [
{"sTitle": "Member No", "mData": "mno"},
{"sTitle": "Member Name", "mData": "pname"},
{"sTitle": "Amount", "mData": "amount"},
{"sTitle": "Month", "mData": "months"},
{"sTitle": "Payment Date", "mData": "paydate"},
]
});
data.forEach(function(recordInLoop)
{
amount += Number(recordInLoop.amount);
});
$('#amount').val(amount);
},
error: function (xhr) {
console.log('Request Status: ' + xhr.status );
console.log('Status Text: ' + xhr.statusText );
console.log(xhr.responseText);
var text = $($.parseHTML(xhr.responseText)).filter('.trace-message').text();
// Reset text box
$('#from_date').val('');
$('#to_date').val('');
console.log(text)
}
});
}
</script>
OR
$('#from_date').datepicker('setDate', null);
$('#to_date').datepicker('setDate', null);

Related

Datatable default ordering not applying

I have this code for jQuery Datatables, it works fine, everything is working as it should aside from the order function is not sorting the column on page load (or at all).
What am I doing wrong here? I've read Datatables documentation and this appears to be correct.
$(document).ready(function() {
$('#data').DataTable( {
"ajax": {
"dataType": 'json',
"url": "package.json",
"dataSrc": "search_result",
"order": [ 0, "desc" ]
},
"columns": [
{ "data": "num" },
{ "data": "domain_name",
"render": function(data, type, row, meta)
{
if(type === 'display')
{
data = '<a class="intel_link" href="http://www.' + data + '" target="_blank">' + data + '</a>';
}
return data;}
},
{ "data": "query_time"},
{ "data": "create_date" },
{ "data": "update_date" },
{ "data": "expiry_date" }
]
} );
} );
Problem is with sort attr, its written inside ajax block.
$(document).ready(function() {
$('#data').DataTable( {
"ajax": {
"dataType": 'json',
"url": "package.json",
"dataSrc": "search_result"
},
"order": [ 0, "desc" ]
"columns": [
{ "data": "num" },
{ "data": "domain_name",
"render": function(data, type, row, meta)
{
if(type === 'display')
{
data = '<a class="intel_link" href="http://www.' + data + '" target="_blank">' + data + '</a>';
}
return data;}
},
{ "data": "query_time"},
{ "data": "create_date" },
{ "data": "update_date" },
{ "data": "expiry_date" }
]
} );
} );
For more detail ref Datable Order

How to make Datatable Jquery dynamically

I need to make a table dynamically with DataTable Jquery, the table must be Server-side processing type and in the same request (Ajax) and answer the columns are made and obviously the results.
DatosColumna=""//Json with Response of ajax
$('#table_query_info').dataTable({
columnDefs: DatosColumna,//Here its the headers
destroy: true,
processing: true,
serverSide: true,
ajax: {
url: myBaseUrl + "consults/find_docs",
type: "post",
data: function (d) {
d.datos = make_info()//Send Json with info
},
statusCode: {
200: function (resp) {
alert("OK");//That Good
}
}
}
});
I tried with this code but it has not worked
Thank you very much
steps for resolution:
make a html code
<table class="table" id="tablaindex" style="width:100%"></table>
Obtengo las columnas, antes de inicializar la tabla
$.ajax({
type: "POST",
url: "AtencionTurno/ColumnasDatatable",
data: TblOficina,
success: function (response) {
inicializarTabla(response);
}, error: function (request, status, error) {
console.log("Error");
}
});
The reques obtain the follow json
[
{
"title": "Column 1",
"data": "Id_Turno",
"orderable": false
},
{
"title": "Column 2",
"data": "Turno",
"orderable": false
},
{
"title": "Column 3",
"data": "Clasificacion",
"orderable": false
},
{
"title": "Column 4",
"data": "Concepto",
"orderable": false
},
{
"title": "Column 5",
"data": "Hora",
"orderable": false
}]
now I initialize the table with the columns that were obtained
inicializarTabla = function (columnas) {
var dataTable = $('#tablaindex').DataTable({
"processing": true,
"serverSide": true,
stateSave: true,
orderable: false,
"order": [],
columns: columnas,
"lengthChange": false,
searching: false,
colReorder: false,
"ajax": {
url: "AtencionTurno/IndexTurnos",
type: "post",
data: TblOficina
}
});
};
response from server:
{
"draw": "1",
"recordsTotal": 4,
"recordsFiltered": 4,
"data": [
{
"Id_Turno": "358",
"Turno": "ALAT1",
"Clasificacion": "euismod",
"Concepto": "Convallis",
"Hora": "11:00:12",
"Tiempo_Espera": "2018/07/03 11:00:12",
"Tipo_Cliente": "Calendario",
"Transferencia": "",
"null": "358"
},
{
"Id_Turno": "354",
"Turno": "ALAK23",
"Clasificacion": "euismod",
"Concepto": "Pagos",
"Hora": "16:36:14",
"Tiempo_Espera": "2018/06/29 16:36:14",
"Tipo_Cliente": "Utiles Escolares ",
"Transferencia": "",
"null": "354"
}
]
}

Jquery Datatables same result

Using Server side processing, with Ignited Datatables, getting the same result set no mater the action I take no other errors are returned.
The page example: I haven't given the server a name can't include link..
> http://104.200.17.5/BotController
JS code
$(document).ready(function() {
var oTable = $('#big_table').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": 'BotController/IpTest',
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"iDisplayStart ":20,
"oLanguage": {
"sProcessing": "assets/images/ajax-loader_dark.gif'>"
},
"fnInitComplete": function() {
//oTable.fnAdjustColumnSizing();
},
'fnServerData': function(sSource, aoData, fnCallback)
{
// console.log(fnCallback);
$.ajax
({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
});
}
} );
});
The server call:
public function IpTest()
{
//ob_clean();
$this->datatables->select('ID,Voting_ID,User_IP,X_IP')
->unset_column('ID')
->from('User_IP_check');
echo $this->datatables->generate();
}
The solution is to use this, and bind all your column names into mData.
"aoColumns": [{
"mData": "col_name_1"
}, {
"mData": "col_name_2"
}, {
"mData": "col_name_3"
}, {
"mData": "col_name_3"
}
],

jQuery.msgBox() plugin. How to send data to /users/login to login user

I am trying to use the following jQuery plugin (jQuery.msgBox()) to perform login to a CakePHP site, but I am confused on how I need to submit the data to my php function for login and redirect if login successful or display a message if not successful. I would appreciate any help.
This is the jQuery function I am using to display the hidden login box, when a user presses the INSERT key on the keyboard.
jQuery(document).bind('keydown', 'insert', function(e) {
//alert(e.keyCode);
$.msgBox({
type: "prompt",
title: "Administrator Log In",
opacity: 0.7,
inputs: [
{ header: "User Name", type: "text", name: "username" },
{ header: "Password", type: "password", name: "password" },
//{ header: "Remember me", type: "checkbox", name: "rememberMe", value: "theValue" }
],
buttons: [
{ value: "Login" }, {value:"Cancel"}],
success: function (result, values) {
var v = result + " has been clicked\n";
$(values).each(function (index, input) {
v += input.name + " : " + input.value +
(input.checked != null ? (" - checked: " + input.checked) : "") + "\n";
});
alert(v); // for testing purposes. Insert login code below
// =======================================================
// =======================================================
}
});
});
I ENDED UP CHANGING vortextangent'S ANSWER A LITTLE BIT, BUT IT WAS BASED ON HIS ANSWER. SEE BELOW.....
=========================================================================================
jQuery(document).bind('keydown', 'insert', function(e) {
//alert(e.keyCode);
$.msgBox({
type: "prompt",
title: "Administrator Log In",
opacity: 0.7,
inputs: [
{ header: "User Name", type: "text", name: "data[User][username]" },
{ header: "Password", type: "password", name: "data[User][password]" },
//{ header: "Remember me", type: "checkbox", name: "rememberMe", value: "theValue" }
],
buttons: [
{ value: "Login" }, {value:"Cancel"}],
success: function (result, values) {
var v = result + " has been clicked\n";
$(values).each(function (index, input) {
v += input.name + " : " + input.value +
(input.checked != null ? (" - checked: " + input.checked) : "") + "\n";
});
//alert(v);
$.ajax({
url: "/users/login",
type: "post",
data: values,
success: function(responseText, statusText, xhr, $form){ // Trigger when request was successful
//responseLogin
if(responseText == "Success") {
window.location.href = '/users/account';
}else{
//alert("Wrong credentials. Please try again...");
$.msgBox({
title: "Login Error",
content: "Wrong credentials. Please try again...",
type: "error",
buttons: [{ value: "Ok" }]
});
}
}
});
}
});
});
=========================================================================================
Use jQuery ajax method.
jQuery(document).bind('keydown', 'insert', function(e) {
//alert(e.keyCode);
$.msgBox({
type: "prompt",
title: "Administrator Log In",
opacity: 0.7,
inputs: [
{ header: "User Name", type: "text", name: "username" },
{ header: "Password", type: "password", name: "password" },
//{ header: "Remember me", type: "checkbox", name: "rememberMe", value: "theValue" }
],
buttons: [
{ value: "Login" }, {value:"Cancel"}],
success: function (result, values) {
var v = result + " has been clicked\n";
$(values).each(function (index, input) {
v += input.name + " : " + input.value +
(input.checked != null ? (" - checked: " + input.checked) : "") + "\n";
});
alert(v); // for testing purposes. Insert login code below
// =======================================================
$.ajax({
url: "yourloginscript.php",
type: "post",
data: values,
success: function(){ // Trigger when request was successful
window.location.href = 'somewhere'
},
error: function(request, error, errormessage) { // Show error
$("#error").html(error + '\n' + errormessage);
},
complete: otherFunction // When request is completed -no matter if the error or not
});
// =======================================================
}
});
});

How to set id after creating new jstree node?

I'm using jsTree 1.0. And have this code :
$(document).ready(function () {
$("#folders_tree").jstree({
"core": {
"initially_open": ["root"]
}, "html_data": {
"data": '<?= $folders; ?>'
}, "themes": {
"theme": "default",
"dots": true,
"icons": true,
"url": "<?= Yii::app()->request->baseUrl ?>/css/jstree/themes/default/style.css"
}, "contextmenu": {
"items": {
"create": {
"label": "Create",
"action": function (obj) {
this.create(obj);
}, "_disabled": false,
"_class": "add",
"separator_before": false,
"separator_after": false,
"icon": false
}, "rename": {
"label": "Rename",
"action": function (obj) {
this.rename(obj);
}, "_disabled": false,
"_class": "rename",
"separator_before": false,
"separator_after": false,
"icon": false
}, "remove": {
"label": "Delete",
"action": function (obj) {
this.remove(obj);
}, "_disabled": false,
"_class": "delete",
"separator_before": true,
"separator_after": false,
"icon": false
}, "ccp": false
}
},
"plugins": ["themes", "html_data", "ui", "crrm", "contextmenu"]
});
/* Callbacks */
var folders = $("#folders_tree");
folders.bind("create.jstree", function (e, data) {
var parent_id = data.rslt.parent[0].id;
var name = data.rslt.name;
var node = data.args[0];
var dataArray = {
"ref_folder": parent_id,
"name": name
};
var dataString = JSON.stringify(dataArray);
$.ajax({
type: 'POST',
url: '<?= Yii::app()->createUrl('
ajax / createfolder ') ?>',
data: {
data: dataString
}, success: function (jdata) {
var json_data = JSON.parse(jdata);
// Here's! This code is not working. Id is not set.
$(node).attr("id", json_data.new_id);
}, dataType: 'text'
});
});
});
$(node).attr("id", json_data.new_id) // this code is not working.
I'm stuck on this :( How can I set this id?
The node variable must be declared as :
var node = data.rslt.obj;
And called as :
node.attr("id", json_data.new_id);
I would do alert(jdata) in the success callback.
Be sure the server is returning safe JSON and that the actual new_id attribute exists.

Categories