fnServerData is not working - php

Let me make it very simple
on server_processing.php
$aColumns = array('is_active','CompanyName', 'email', 'phone_no', 'web_address','id' );
$sIndexColumn = "id";
$sTable = "inf_company";
also set connection to db
Now the jquery function is
"sAjaxSource": "server_processing.php",
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
// Bold the grade for all 'A' grade browsers
if ( aData[0] != 0 )
{
$('td:eq(0)', nRow).html( '<input type="checkbox" name="delid[]" value="'+ aData[5] +'" />' );
}
if ( aData[5] != 0 )
{
// $('td:eq(4)', nRow).html( '<b>A</b>' ); // You can add your link here!!
$('td:eq(5)', nRow).html( '<img src="./images/del.png" alt="delete">' );
}
return nRow;
},
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "CompanyName",
"value": "NATIONAL" } );
}
simple i want to search company name national..but it is not working

When I checked out fnServerData example in datatables.net, the params (i.e. aoData) that would be posted is assembled in fnServerParams instead of fnServerData itself.
So I think you should move the below:
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "as_strno",
"value": $('#strno').val() },
{ "name": "as_temp_ref",
"value": $('#as_temp_ref').val() });
aoData.push( { "name": "dateaddedSto",
"value": $('#listings_row #dateaddedSto').val() });
}

Related

Extract Data from JSON and display in SWAL alert

I am having problems while trying to show info from a Json to an alert, this is my code.
function check_values_chbx(){
var pre_insc = [];
}).done(function(response){
for(i=0; i<response.length; i++){
pre_insc[i] = response[0]['personas'][i]['name']+" "+response[0]['personas'][i]['ap_pat']+" "+response[0]['personas'][i]['ap_mat'];
}
alert(pre_insc[1]);
swal({
title: "Detalles de inscripcion",
text: "Participantes que quedaran inscritos: \n\n"+pre_insc.join('\n')+"\n\nCategoria:",
buttons: true,
dangerMode: false,
}).then((willDelete) => {
if (willDelete) {
swal("Participantes registrados con exito, mucha suerte!", {
icon: "success",
});
}else {
location.reload();
}
});
});
}
And this is my JSON
[
{
"personas": [
{
"name": "Jessica",
"ap_pat": "BocaNegra",
"ap_mat": "Garcia"
},
{
"name": "Fernando",
"ap_pat": "Soto",
"ap_mat": "Olivas"
}
],
"evento": [
{
"name": "Carrera larga"
}
],
"categoria": [
{
"name": "Juvenil"
}
]
}
]
I need to print each name like:
swal("name1\n"+name2\n"+etc").
Please if someone could help me it will be very helpful, have a nice day.
You can use the below script which recursively iterates a json object if it finds an array or Object until it finds the text for the given property and then print them all if the property name is name with \n separator, you can add the following inside your script file and pass it the response that you are receiving and use the returned names with your sweetAlert, just make sure you pass the response to the function like below
names = jsonParser.getNames(response[0]);
Add the below in you script
var jsonParser = {
isObject: function (property) {
return property && {}.toString.call(property) === '[object Object]';
},
isArray: function (property) {
return property && {}.toString.call(property) === '[object Array]';
},
getNames: function (errors) {
var data = "";
for (let message in errors) {
var errorSet = errors;
if (errorSet.hasOwnProperty(message)) {
if (jsonParser.isArray(errorSet[message]) || jsonParser.isObject(
errorSet[message])) {
data += jsonParser.getNames(errors[message]);
} else if (message == 'name') {
data += errorSet[message] + "\n";
}
}
}
return data;
}
};
An example to read the names from your given response is given below.
var jsonParser = {
isObject: function(property) {
return property && {}.toString.call(property) === '[object Object]';
},
isArray: function(property) {
return property && {}.toString.call(property) === '[object Array]';
},
convertToString: function(errors) {
var data = "";
for (let message in errors) {
var errorSet = errors;
if (errorSet.hasOwnProperty(message)) {
if (jsonParser.isArray(errorSet[message]) || jsonParser.isObject(
errorSet[message])) {
data += jsonParser.convertToString(errors[message]);
} else if (message == 'name') {
data += errorSet[message] + "\n";
}
}
}
return data;
}
};
var response = [{
"personas": [{
"name": "Jessica",
"ap_pat": "BocaNegra",
"ap_mat": "Garcia"
},
{
"name": "Fernando",
"ap_pat": "Soto",
"ap_mat": "Olivas"
}
],
"evento": [{
"name": "Carrera larga"
}],
"categoria": [{
"name": "Juvenil"
}]
}];
var names = '';
names = jsonParser.convertToString(response[0]);
console.log(names);
Your final script should look like
function check_values_chbx(){
var pre_insc = [];
}).done(function (response) {
var names = jsonParser.getNames(response[0]);
swal({
title: "Detalles de inscripcion",
text: "Participantes que quedaran inscritos: \n\n" + names +
"\n\nCategoria:",
buttons: true,
dangerMode: false,
}).then((willDelete) => {
if (willDelete) {
swal("Participantes registrados con exito, mucha suerte!", {
icon: "success",
});
} else {
location.reload();
}
});
});
Hope this helps you out

Datatable Show/Hide Checkbox is not working proferly

I am using DataTable to display the data. All the column names with check box is displaying when i click show and hide button. When i uncheck all the column and when i try to check the column name at that time the first column is getting copied or getting displayed in the all the row values.
Following is my code which i written.
$('#datatable_col_reorder').dataTable({
"processing": true,
"sAjaxSource": "<?php echo $config['ajaxUrlPath'];>json.php",
"bFilter" : true,
"fnServerData": function ( sAjaxSource , aoData, fnCallback ) {
aoData.push( { "name": "eventName", "value": $('#eventName').val() });
aoData.push( { "name": "et", "value": $('#Type').val() });
aoData.push( { "name": "vn", "value": $('#address').val() });
aoData.push( { "name": "da", "value": $('#date_added').val() });
aoData.push( { "name": "ti", "value": $('#time_added').val() });
aoData.push( { "name": "st", "value": $('#status').val() });
aoData.push( { "name": "br", "value": $('#status1').val() });
aoData.push( { "name": "cr", "value": $('#status2').val() });
aoData.push( { "name": "pr", "value": $('#spercentage').val() });
// etc
$( "#status2,#address,#spercentage" ).keyup(function() {
var table = $('#datatable_col_reorder').DataTable();
table.ajax.reload();
});
$( "#status,#Type,#date_added,#time_added,#status1,#status2" ).change(function() {
var table = $('#datatable_col_reorder').DataTable();
table.ajax.reload();
});
$.getJSON( sAjaxSource, aoData, function (json) { console.log(json); fnCallback(json) } );
},
"sDom":"<'col-sm-1 col-xs-1 col-md-1 col-lg-1 showHidebutton'C><'dt-toolbar'r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-sm-6 col-xs-12'p>>",
"autoWidth" : true,
"rowCallback": function( nRow, aData, iDisplayIndex ) {
// responsiveHelper_datatable_tabletools.createExpandIcon(nRow);
$('td:eq(0)', nRow).html(''+aData[0]+'');
return nRow;
},
"preDrawCallback" : function() {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_datatable_col_reorder) {
responsiveHelper_datatable_col_reorder = new ResponsiveDatatablesHelper($('#datatable_col_reorder'), breakpointDefinition);
}
},
"drawCallback" : function(oSettings) {
responsiveHelper_datatable_col_reorder.respond();
}
});
When i uncheck all and when i try to recheck each checkboxes, at that time the first column values are getting displayed in all other column like type,status,address etc.
Example: Consider Name: XYZ, After deselecting checkboxes if i try to recheck at that time the each column values is showing "XYZ" in status,address columns.
Thanks in advance.

Dynamically load data from server to "select" type input fields in datatables

I have a PHP code that is being called by the function loader that is only triggered on onInitCreate event in datatable. What I want to do is that when the user clicks the add button it must load the faculty Names in the select field.
I've already tried this code but it returns nothing or should I say a null value. I'm confident that it should return exactly one row.
This is my PHP code that gets the faculty names and return it.
getFacultyNames.php
<?php
error_reporting(-1);
require_once("config.php");
$sql="SELECT lastName, firstName, middleName FROM table_faculty";
$result = mysql_query($sql);
$stack=array();
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
$name = $row[0]." ,".$row[1]." ".$row[2];
array_push($stack,array("label" => $name, "value" => $name));
}
echo json_encode($stack); //here it returns [{"label":"Last ,First Middle","value":"Last ,First Middle"}]
?>
jquery code:
function loader(){
$.ajax({
"url": 'php/getFacultyNames.php',
"async": false,
"dataType": 'json',
"success": function (json) {
console.log( json );
//the getFacultyNames.php is now returning correct values,
//but how would I be able to get the value of the json code properly?
//it always throws an error ""parsererror" SyntaxError
//is it proper to have a code `return json;` in this success function?
},
"error" : function( jqXHR, textStatus, errorThrown ){ console.log( jqXHR, textStatus, errorThrown ); }
});
}
This is my editor initialization code:
var editor = new $.fn.dataTable.Editor( {
"ajaxUrl": "php/table.facultyloading.php",
"domTable": "#facultyloading",
"events": {
"onInitCreate":function (){
editor.add( {
"label": "Assign to Faculty",
"name": "facultyName",
"type": "select",
"ipOpts":loader() // Returns array of objects - .ajax() with async: false
});
}
},
"fields": [
{
"label": "Subject Name",
"name": "name",
"type": "select",
"ipOpts": [
{
"label": "sample",
"value": "sample"
}
]
},
{
"label": "Day",
"name": "day",
"default": "Monday",
"type": "checkbox",
"ipOpts": [
{
"label": "Monday ",
"value": "Monday "
},
{
"label": " Tuesday ",
"value": " Tuesday "
},
{
"label": " Wednesday ",
"value": " Wednesday "
},
{
"label": " Thursday ",
"value": " Thursday "
},
{
"label": " Friday ",
"value": " Friday "
},
{
"label": " Saturday",
"value": " Saturday"
}
],
"separator": "|"
},
{
"label": "Start Time",
"name": "startTime",
"type": "text"
},
{
"label": "End Time",
"name": "endTime",
"type": "text"
},
{
"label": "Room",
"name": "room",
"type": "text"
}
]
} );
I can't seem to figure out what is wrong.Am I missing something? Can you help me?
Thanks in advance!
I've converted the mysql function to PDO_MySQL and finally it works this is my new getFacultyNames.php and I've also modified my jquery code a bit. Thanks for all your help! :)
getFacultyNames.php
<?php
error_reporting(-1);
require_once("config.php");
$stack=array();
$stmt = $dbh->prepare("SELECT lastName, firstName, middleName FROM table_faculty");
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$name = $row['lastName']." ,".$row['firstName']." ".$row['middleName'];
array_push($stack,array($name,$name));
}
echo json_encode($stack);
}
?>
jquery code
function names(){
var test= new Array({"label" : "a", "value" : "a"});
test.splice(0,1);
$.ajax({
"url": 'php/getFacultyNames.php',
"async": false,
"dataType": 'json',
"success": function (json) {
for(var a=0;a < json.length;a++){
obj= { "label" : json[a][0], "value" : json[a][1]};
test.push(obj);
}
},
"error" : function( jqXHR, textStatus, errorThrown ){ console.log( jqXHR, textStatus, errorThrown ); }
});
return test;
}
Add die to end of getFacultyNames.php.
echo json_encode($stack);
die;
UPDATE
Try to remove "dataType": 'json' and set in callbaks:
try {
json = JSON.parse(data);
}
catch (e) {
console.log("Parse error:"+e);
};
use this
function loader(){
var responseText = $.ajax({
"url": 'php/getFacultyNames.php',
"async": false,
"dataType": null,
"error" : function( jqXHR, textStatus, errorThrown ){
console.log( jqXHR, textStatus, errorThrown );
}
}).responseText;
return $.parseJSON(responseText)
}
This will do the AJAX call and return you the properly formatted JSON object.

jquery jeditable save to database

I am using the following code to enable live edit with jeditable:
<script type="text/javascript">
$(document).ready(function(){
var aDataSet = [
["klad1111.com","<img src='world/se.png' />","-","0","0","0%","0"],
["klad2222.com","<img src='world/dk.png' />","2012-12-05","1","3","300%","15"],
["klad33333.com","<img src='world/dk.png' />","-","0","0","0%","0"],
["klad6666.info","<img src='world/dk.png' />","-","0","0","0%","0"],
["klad44444.info","<img src='world/dk.png' />","-","0","0","0%","0"],
["klad5555.com","<img src='world/se.png' />","-","0","0","0%","0"],
];
$('#dynamic').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
$('#example').dataTable( {
"aaData": aDataSet,
"aoColumns": [
{ "sTitle": "Namn" },
{ "sTitle": "Land" },
{ "sTitle": "Uppdaterad" },
{ "sTitle": "Neutrala Posts", "sClass": "center" },
{ "sTitle": "Post / Client", "sClass": "center" },
{ "sTitle": "Ratio", "sClass": "center" },
{ "sTitle": "Total Posts", "sClass": "center" }
]
} );
/* Init DataTables */
var oTable = $('#example').dataTable();
/* Apply the jEditable handlers to the table */
$('td', oTable.fnGetNodes()).editable( 'editable_ajax.php', {
"callback": function( sValue, y ) {
var aPos = oTable.fnGetPosition( this );
oTable.fnUpdate( sValue, aPos[0], aPos[1] );
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oTable.fnGetPosition( this )[2]
};
},
"height": "14px"
} );
});
</script>
Live edit kind of works, when i click on a cell i get up a input box. But the save part is not working.. I am not sure how to update my database accordingly..
Any ideas?

data table row details with select filter and export to Excel

I want to add row details option with filtering and exporting to an Excel document. After adding export to program row details function are not working.
Here is my code:
<script type="text/javascript" language="javascript" class="init">
/* Formatting function for row details - modify as you need */
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full name:</td>'+
'<td>'+d.name+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extension number:</td>'+
'<td>'+d.extn+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extra info:</td>'+
'<td>And any further details here (images etc)...</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function() {
var table_data_json = '[<?php for($i=0;$i<5;$i++){?>{"name":"Tiger Nixon","position":"System Architect","salary":"$320,800","start_date":"2011/04/25","office":"Edinburgh","extn":"5421"},<?php }?>{"name":"Garrett Winters","position":"Accountant","salary":"$170,750","start_date":"2011/07/25","office":"Tokyo","extn":"8422"},{"name":"Ashton Cox","position":"Junior Technical Author","salary":"$86,000","start_date":"2009/01/12","office":"San Francisco","extn":"1562"}]';
var table = $('#example').DataTable( {
"data": JSON.parse(table_data_json),
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']],
"dom": 'T<"clear">lfrtip',
"tableTools": {
"sSwfPath": "swf/copy_csv_xls_pdf.swf",
"aButtons": [
{
"sExtends": "xls",
"sButtonText": "Export to Spreadsheet",
"mColumns": "visible",
"oSelectorOpts": { filter: 'applied', order: 'current' },
"bFooter":false
}
],
"oSelectorOpts": {
"filter": "applied"
}
},
initComplete: function () {
var r = $('#example tfoot tr');
r.find('th').each(function(){
$(this).css('padding', 8);
});
$('#example thead').append(r);
$('#search_0').css('text-align', 'center');
this.api().columns([1,7]).every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
</script>

Categories