I want to set up a datatable on my website and I found a table I want to use here and I have been trying to convert it over to what I need. I have not had much success in this endeavor. My current situation is the table is not populating with rows from a database table and I am getting a json response error. I can open the inspector look at the php file that queries the database returns json data and I can see that I am returning data in the format
{"data":[
{"ssn":"100192686","dob":"1977-02-01","fn":"Latoyia","mi":"H","ln":"Herdon"},
{"ssn":"100263201","dob":"1962-06-15","fn":"Adena","mi":"M","ln":"Couch"}
]}
which according to a json validator is valid json but when I reload my page I get an error
"table id=example - Invalid JSON response".
So if the json data is in the correct format but is not being returned correctly what do I do? here is a gihub for the project. I have included the mysql database file I am working with as well as a text file that has XHR results in it. I feel like this line $('#example').DataTable( { javascript is where my issue is
<?php
include_once 'header.php';
?>
<script src = 'https://code.jquery.com/jquery-1.12.4.js'></script>
<script src = 'https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js'></script>
<script src = 'https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js'></script>
<script src = 'https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js'></script>
<script src = 'JS/dataTables.editor.min.js'></script>
<link rel = "stylesheet" href = "https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<link rel = "stylesheet" href = "https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
<link rel = "stylesheet" href = "https://cdn.datatables.net/select/1.2.5/css/select.dataTables.min.css">
<link rel = "stylesheet" href = "https://editor.datatables.net/extensions/Editor/css/editor.dataTables.min.css">
<section class="main-container">
<div class="main-wrapper">
<h2>Home</h2>
<?php
if (isset($_SESSION['u_id'])) {
$sql = "SELECT * FROM employee;";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0){
echo
"<table id='example' class='display' cellspacing='0' width='100%'>
<thead>
<tr>
<th></th>
<th>ssn</th>
<th>dob</th>
<th>first</th>
<th>MI</th>
<th>last</th>
</tr>
</thead>";
}
}
?>
</div>
</section>
<script>
console.log("In the script open");
var editor; // use a global for the submit and return data rendering in the examples
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: "infograb.php",
table: "#example",
fields: [ {
label: "Social#:",
name: "ssn"},
{
label: "DOB:",
name: "dob"},
{label: "First Name:",
name: "fn"},
{
label: "Middle Initial:",
name: "mi"},
{
label: "Last Name:",
name: "ln"
}
]
} );
$('#example').on( 'click', 'tbody td', function (e) {
var index = $(this).index();
if ( index === 1 ) {
editor.bubble( this, ['fn', 'mi', 'ln'], {
title: 'Edit name:'
} );
}
else if ( index === 2 ) {
editor.bubble( this, {
buttons: false
} );
}
else if ( index === 3 ) {
editor.bubble( this );
}
} );
var testData = [{
"ssn": "98727748",
"dob": "2016-02-05",
"fn": "jake",
"mi": "a",
"ln": "butler"
}];
$('#example').DataTable( {
dom: "Bfrtip",
ajax:{
url: 'infograb.php',
type: 'POST',
data: {
json: JSON.stringify({ "data": testData })
},
dataSrc: 'data'
},
columns: [
{//sets the checkbox
data: null,
defaultContent: '',
className: 'select-checkbox',
orderable: false
},
{ data: "dob" },
{ data: "ssn" },
{ data: "fn" },
{ data: "mi" },
{ data: "ln" },
],
order: [ 1, 'asc' ],
select: {
style: 'os',
selector: 'td:first-child'
},
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
} );
} );
console.log("End script");
</script>
<?php
include_once 'footer.php';
?>
and here is the php file that queries the database and returns(allegedly) the json data
<?php
include_once 'dbconn.php';
$rows = array();
$sql = "SELECT * FROM employee";
$result = $conn->query($sql) or die("cannot write");
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
echo "<pre>";
print json_encode(array('data'=>$rows));
echo "</pre>";
?>
I have been at this for about 24 hours now, and I feel like I have a bonehead mistake here I just can't figure it out. Any help would talk me down off the cliff at this point.
Datatables can be a pain and it's worthwhile to make sure you read the documents provided by them as much as you can.
I can see 2 issues running over your code without running tests. First one is infograb.php won't save any data sent to it because all it does is return data when it's loaded. Secondly you are using the initiation code of the datatable to try and send data (presumably for the inline editing as you don't seem to require any variables to be sent for the data requested). My first step would be taking it back a step:
ajax:{
url: 'infograb.php',
type: 'POST',
data: {
json: JSON.stringify({ "data": testData })
},
dataSrc: 'data'
},
Should go back to
ajax:{
url: 'infograb.php',
},
Remove the pre tags from infograb.php as well as they are unnecessary.
That should load the data into the table for you. You can then start working on the editing side.
Worthwhile Reading and Documentation:
Ajax sourced data
PHP libraries
DataTables Editor 1.7.3 - PHP 5.3+ libraries
Related
Here is all the code related to the #results table:
jQuery(document).ready(function) {
editor = new jQuery.fn.dataTable.Editor( {
ajax: "<?php echo $full_dir . '/ajax_call.php'; ?>",
table: "#results",
fields: [ {
label: "Mfg ID",
name: "ball_mfg.mfgID"
}, {
label: "Mfg name:",
name: "ball_mfg.name"
}, {
label: "Model #",
name: "ball_model.modelID"
}, {
label: "Model Name:",
name: "ball_model.name"
}
]
} );
jQuery('#results').DataTable( {
"pagingType": "full_numbers",
dom: "Bfrtip",
ajax: {
url: "<?php echo $full_dir . '/ajax_call.php'; ?>",
type: 'POST'
},
columns: [
{ "render": function ( data, type, full, meta ) {
return '<input type="radio" name="select_model" class="radio1 my_input" data-modelID="'+full.ball_model.modelID+'">';
}}, // here's a radio button, modify to use data to populate it,
{ data: "ball_mfg.name" },
{ data: "ball_model.name" }
],
select: false,
buttons: [
]
} );
This only displays the standard Previous, page numbers and Next button. You can view the output at https://www.bowling-tracker.com/bowl/bowling-resources/bowling-ball-information
My preference would actually be to have an input box. You'll note that I have
<script type="text/javascript" src="https://cdn.datatables.net/plug-ins/1.10.16/pagination/input.js"></script>
in the header and I've tried to use
"pagingType":"input",
as well but it doesn't seem to matter which paging Type that I use, it simply does not change the pagination buttons.
I'm using DataTables Editor to generate this because it needs to be run on the server side (due to returned results) and so I can display only a few tables (which are joined).
Look at the source code that loads. There is no "pagingType". Change it to input so we can see the output when it is written correctly.
I'm completely new to web technologies,
I have a table that retrieves data from a database and they are displayed with bootstrap table.
Check out the interface image
I have usernames;
each username has their own image.
I have the images for every username stored online.
with the following naming:
username= 111
has an image with the name 111.jpg
stored on localhost/images/111.jpg
What I want to achieve is when I hover over any username in the table, their image is displayed.
list-user.php file
<?php
require 'db.php';
$sqltran = mysqli_query($con, "SELECT * FROM users ")or die(mysqli_error($con));
$arrVal = array();
$i=1;
while ($rowList = mysqli_fetch_array($sqltran)) {
$name = array(
'num' => $i,
'user'=> $rowList['username'],
);
array_push($arrVal, $name);
$i++;
}
echo json_encode($arrVal);
mysqli_close($con);
?>
`
what matters from index.php file
<script type="text/javascript">
var $table = $('#table');
$table.bootstrapTable({
url: 'list-user.php',
search: true,
pagination: true,
buttonsClass: 'primary',
showFooter: true,
minimumCountColumns: 2,
columns: [{
field: 'num',
title: '#',
sortable: true,
},{
field: 'user',
title: 'Username',
sortable: true,
}, ],
});
</script>
Thats what I'm trying to accomplish something like this
What I want to accomplish (IMAGE )
I'm using datatable plugin and want to refresh table by ajax. I've read here to make my ajax return shows in table but it doesn't work. Here is my html code:
<button type="button" onclick="rld()">test</button>
<table id="sample_1">
<thead>
<tr>
<th> 1 </th>
<th> 2 </th>
<th> 3 </th>
</tr>
</thead>
</table>
My java function:
function rld(){
var table = $('#sample_1').DataTable( {
ajax: '<?php echo site_url('admin/test'); ?>',
deferRender: true,
columns: [
{ data: '1' },
{ data: '2' },
{ data: '3' }
],
rowId: 'extn',
select: true,
dom: 'Bfrtip',
buttons: [
{
text: 'Reload table',
action: function () {
table.ajax.reload();
}
}
]
} );
}
I can't get what the problem is. there in no alerts but in the console i get TypeError: f is undefined
and TypeError: c is undefined
Which i don't know why cause my json return is correct (checked in [JSONLint][3]).
Thanks in advance.
Thank you all for your attention :)
Found that i didn't call where the data goes when returned as json and the json field's name isn't equal to the column data field name. So make this adjustment:
function reload_table(){
var table = $('#sample_1').DataTable();
table.destroy();
var table = $('#sample_1').DataTable( {
"processing": true,
"dataType": 'json',
ajax: '<?php echo site_url('admin/relaod_table'); ?>',
deferRender: true,
columns: [
{ data: 'user_firstname' },
{ data: 'user_lastname' },
{ data: 'user_status' },
{ data: 'user_created_date' },
],
dom: 'Bfrtip',
buttons: [
{
text: 'Reload table',
action: function () {
table.ajax.reload();
}
}
]
} );
}
var table = $('#accessRequest').DataTable({
"dom": 'Blfrtip',
"ajax": "Editor-PHP-1.5.1/php/editor-serverside.php",
"columns": [
{ //special column for detail view
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ data: "DT_RowId",
render: function ( data ) {
return data.replace( 'row_', '' );
}
},
{ data: null,
render: function ( data, type, row ) {
// Combine the first and last names into a single table field
return data.first+' '+data.last;
}
},
{ "data": "phone" },
{ "data": "responsibleParty" },
{ "data": "email" },
{ "data": "building" },
{ "data": "typeOfWork" },
{ "data": "startTime" },
{ "data": "endTime" },
{ "data": "description" },
{ "data": "dockNeeded" },
{ "data": "numPeople" },
{ "data": "numTrucks" },
{ "data": "requestPlaced" },
{ "data": "updatedAt" },
{ "data": "approved" },
{ "data": "approvedBy" },
{ "data": "approvedAt" },
{ "data": null }
],
"aoColumnDefs": [
{
"aTargets": [-1],
"mData": null,
"mRender": function (data, type, full) {
return '<button id="ApprovalButton" onclick="$.post(\'extra.php\', \'approve_request\')" action="extra.php" method="post"> Process </button>';
//Send post request
}
}
],
"order": [[1, 'asc']],
select: true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
});
I have a string of code (above) in which I am creating a table to contain information. On the line that says "//send post request" I'm trying to make it so the button directly above it sends a post request to a separate file called "extra.php", and despite what I've done I haven't been able to that.
I've tried using a submit button in an input form, but that didn't work. I've tried a lot of different things, but I can't seem to get it to work. Any help would be appreciated.
There is already a file (extra.php) that is capable of receiving a post request and acting on it once it has received it. I'm attempting to create a button in HTML on a page, that when clicked posts 'approve_request' to the file "extra.php"
Sorry, I'm new to both coding and this website, there's probably something simple that I'm not doing.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
header('Access-Control-Allow-Origin: *');
$id = intval($_POST['id']);
$con = mysql_connect("RequestAccess.db.10160035.hostedresource.com","RequestAccess","br#6HeCher");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("RequestAccess", $con);
//if action sent is approve set request as apporved
if(isset($_POST['approve_request'])){
$sql = "UPDATE AccessRequests
SET approved='1', approvedAt=current_timestamp
WHERE AccessID='" . $_POST['approve_request']."'";
$results = mysql_query($sql);
}
//else action sent must be for child rows so populate child row
else {
}
This is the section responsible for handling the post request, if that helps.
First of all, some browsers block sending requests with JS so add this on top of your PHP code
header('Access-Control-Allow-Origin: *');
Now you can send a request without problems.
$.post(url ,{
postItem1 : postValue1,
postItem2: postValue2
//You have to define postItem1 and 2 in your PHP code -> $_POST["postItem1"] -> this will return postValue1
}, function(data, status){
//success
}).fail(function() {
//failed
});
I am putting together a simple join query using Datatables Editor however am getting errors which I don't understand. My code is below:
HTML
<!-- Actions -->
<div id="divActions" class="tab-pane fade">
<ul class="nav nav-list">
<!-- Actions Tab Header -->
<legend id="lgdActions">Actions</legend>
<table id="tblActions" class="display" cellspacing="0" width="100%"></table>
</ul>
</div>
Javascript
Actions Datagrid
$('#tblActions').DataTable({
dom: "Tfrtip",
lengthChange: false,
bAutoWidth: false,
jQueryUI: true,
bProcessing: true,
bServerSide: true,
ajax: {
url: "dataGridQuery.php",
data: { "gridNumber": 2 },
type: 'POST'
},
columns: [
{ title: "Action ID", data: "tblActions.actionID", width: "10%" },
{ title: "Time", data: "tblActions.actionTime" },
{ title: "Action Taken", data: "tblActions.actionTaken" },
{ title: "User", data: "tblUsers.userID" }
]
tableTools: {
sRowSelect: "os",
aButtons: [
{ sExtends: "editor_create", editor: editor1 },
{ sExtends: "editor_edit", editor: editor1 },
{ sExtends: "editor_remove", editor: editor1 }
]
}
});
PHP
// Obtain Action Grid
if(isset($_GET['gridNumber']) && $_GET['gridNumber']==2){
//
$data = Editor::inst( $db, 'tblActions' )
->field(
Field::inst( 'tblActions.actionID' ),
Field::inst( 'tblActions.actionTime' ),
Field::inst( 'tblActions.actionTaken' ),
Field::inst( 'tblActions.actionUserID' ),
Field::inst( 'tblUsers.userID' )
)
->leftJoin( 'tblUsers', 'tblUsers.userID', '=', 'tblActions.actionUserID' )
->process($_POST)
->data();
//
if ( ! isset($_POST['action']) ) {
// Get a list of sites for the `select` list
$data['tblUsers'] = $db
->selectDistinct( 'tblUsers', 'userID as value, userID as label' )
->fetchAll();
}
// Echo
echo json_encode( $data );
}
The errors I receive when running this code are:
Errors {"error":"SQLSTATE[42S22]: Column not found: 1054 Unknown
column 'tblActions.id' in 'field
list'","data":[],"tblUsers":[{"value":"1","label":"1"},{"value":"2","label":"2"}]}
DataTables warning: table id=tblActions - Invalid JSON response. For
more information about this error, please see
http://datatables.net/tn/1.
This code was from a sample provide when downloading the Editor v1.3.1. I am somewhat familiar with the plug-in however find it perplexing when such an error occurs. Any help would be much appreciated.
Thanks :)
You have to change the name of the primary key.
I think if you add the following somewhere.
"idSrc": "actionID",
http://datatables.net/forums/discussion/19199/custom-primary-key
This also may work
$data = Editor::inst( $db, 'tblActions' )
->pkey( 'actionID' )