This is my DataTable code:
$('#open').DataTable( {
select: true,
"processing": true,
"sAjaxSource": "booked1.php",
"serverside": true,
"columns" :[ {
"data" : "name"
}, {
"data" : "date1"
}, {
"data" : "bookingtoken"
}, {
"data" : "insurance"
}]
} );
This is my ajax call :
$("#submit").on('click', function () {
$('#loadarModal').modal({backdrop: 'static', keyboard: false});
var date = $("#date").val();
//alert(date);
if (date == '') {
$("#dateText").show();
$("#dateText").html("Please select date");
$("#loadarModal").modal('hide');
} else {
$("#dateText").hide();
//alert("can processd");
var data = $("#form").serialize();
$.ajax({
type: 'POST',
url: 'booked1.php',
data: {
date: date
},
cache: false,
dataType: "html",
success: function (response) {
alert(response);
if(response==''){
}
$("#booking").html(response);
$("#loadarModal").modal('hide');
}
});
}
});
This is my PHP Script:
include 'd_b_con.php';
if(isset($_POST['date'])){
$date=$_POST['date'];
$query=mysqli_query($conn,"select date as date ,tokenno as tokenno ,inusrance as inusrance,bookingtoken as bookingtoken ,
fname as fname,lname as lname , status as status from at_booking where date='$date'");
$data=array();
while($row1=mysqli_fetch_array($query)){
$data[] = $row1;
$date1=$row1['date'];
$tokenno=$row1['tokenno'];
$bookingtoken=$row1['bookingtoken'];
$fname=$row1['fname'];
$lname=$row1['lname'];
$status=$row1['status'];
$insurance=$row1['inusrance'];
$name=$fname.' '.$lname;
echo '<tr>';
echo "<td>$name </td>";
echo "<td> $date1 </td>";
echo "<td>$bookingtoken </td>";
echo "<td>$insurance </td>";
echo '</tr>';
$result=array(
"name" => $name,
"date1" => $date,
"bookingtoken" => $bookingtoken,
"insurance" => $insurance
);
echo json_encode($result);
}
This is the first time I am using server side data tables.
I am getting error like "DataTables warning: table id=open - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1"
Can anyone guide me how to use data tables server side for my code.
Try to change this code,
$result = [];
$result[]=array(
"name" => $name,
"date1" => $date,
"bookingtoken" => $bookingtoken,
"insurance" => $insurance
);
echo json_encode($result);
die;
Once check in network->xhr whether you are getting any response or not.
You really overcomplicate this. You should never echo out the actual <tr><td>.. markup, this is why you get the warning. And use mysqli_fetch_assoc instead :
$data = array();
while( $row1 = mysqli_fetch_assoc($query) ){
$row1['name'] = $row1['fname'].' '.$row1['lname'];
$row1['date1'] = $row1['date']; //??
$data[] = $row1;
}
echo json_encode($data);
Update. You will probably need to use
echo json_encode( array('data' => $data) );
If you not set dataSrc to ''.
Related
I encountered a problem fetching my data from my database and display it via DataTables. I found out that most of my data has single and double quotes and other special characters. I tried every escaping functions in PHP but it didn't work. addslashes only retrieves 59 data out of 40,000 data. So far, i have this code:
PHP:
$query = mysqli_query($new_conn, "SELECT * FROM bill_of_materials");
$table = '';
while($row = mysqli_fetch_array($query)) {
$table.= '{
"allotment_code":"'.$row['allotment_code'].'",
"activity":"'.$row['activity'].'",
"category_name":"'.addslashes($row['category_name']).'",
"description":"'.addslashes($row['description']).'"
},';
}
$table = substr($table,0, strlen($table) - 1);
echo '{"data":['.$table.']}';
**jQuery data tables:**
$(function() {
$('#dataTables-example').DataTable( {
"bLengthChange": false,
"pageLength": 50,
"bDeferRender": true,
"bProcessing": true,
"sPaginationType": "full_numbers",
"ajax": base_url('ajax/ajaxGetBOM.php'),
"columns":[
{mData: "allotment_code"},
{mData: "activity"},
{mData: "category_name"},
{mData: "description"}
],
contentType: 'application/json',
dataType: 'json'
});
})
function base_url(path) {
var url = 'https://192.168.3.254/'+path;
return url;
}
The error is like this:
Use json_encode() function to properly encode your response using JSON format.
$query = mysqli_query($new_conn, "SELECT * FROM bill_of_materials");
$data = array();
while($row = mysqli_fetch_array($query)) {
$data[] = array(
"allotment_code" => $row["allotment_code"],
"activity" => $row["activity"],
"category_name" => $row["category_name"],
"description" => $row["description"]
);
}
header("Content-type: application/json");
echo json_encode(array("data" => $data));
i'm beginner in codeigniter. i work using cart library from codeigniter and it's work fine. but i have another values as weight and amount (interger value) in my list cart. example when i adding a same value in twice, just qty and subtotal has increased. the weight and amount just update where i Last input not calculate from old value with new value. how i can solved this..?
i'm using CI v3.1 and datatables for show the list cart,
sorry for my bad english language. best regards :)
here my controller cart
//adding to cart list
public function addbarang()
{
$data = array(
'id' => $this->input->post('id_barang'),
'price' => str_replace('.', '', $this->input->post('harga_barang')),
'qty' => $this->input->post('qty'),
'unit' => $this->input->post('j-unit'),
'name' => $this->input->post('nama_barang'),
'nama_jenis' => $this->input->post('j-nama_jenis'),
'id_jenis' => $this->input->post('j-id_jenis'),
'options' => array('j-berat' => $this->input->post('j-weight'),'j-amount' => $this->input->post('j-amount'))
);
$insert = $this->cart->insert($data);
echo json_encode(array("status" => TRUE));
//echo"<pre>";
//print_r($this->cart->contents());
// echo"<pre>";
}
//show cart list in datatables
public function ajax_list_transaksi()
{
$data = array();
$no = 1;
foreach ($this->cart->contents() as $items){
$row = array();
$row[] = $no;
$row[] = $items["id"];
$row[] = $items["name"];
$row[] = $items["id_jenis"];
$row[] = $items["nama_jenis"];
$row[] = $items["qty"];
$row[] = $items["unit"];
$row[] = $items["options"]["j-berat"];
$row[] = $items["options"]["j-amount"];
$row[] = 'Rp. ' . number_format( $items['price'],
0 , '' , '.' ) . ',-';
$row[] = 'Rp. ' . number_format( $items['subtotal'],
0 , '' , '.' ) . ',-';
//add html for action
$row[] = '<a href="javascript:void(0)" style="color:rgb(255,128,128); text-decoration:none" onclick="deletebarang('
."'".$items["rowid"]."'".','."'".$items['subtotal']."'".')"> <i class="fa fa-close"></i> Delete</a>';
$data[] = $row;
$no++;
}
$output = array(
"data" => $data,
);
echo json_encode($output);
}
my js to show and adding value cart list
//the js to show cart list in html
var table;
$(document).ready(function() {
table = $('#table_transaksi').DataTable({
"paging": true,
"ordering": false,
"info": false,
"searching": false,
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?= site_url('Master_rabp/ajax_list_transaksi')?>",
"type": "POST"
},
"columnDefs": [{
"targets": [ 0,1,2,3,4,5,6 ],
"orderable": false,
}],
});
});
function reload_table()
{
table.ajax.reload(null,false);
}
//the js for adding new cart value
function addbarang()
{
var id_barang = $('#id_barang').val();
var qty = $('#qty').val();
if (id_barang == '') {
$('#id_barang').focus();
}else if(qty == ''){
$('#qty').focus();
}else{
$.ajax({
url : "<?= site_url('Master_rabp/addbarang')?>",
type: "POST",
data: $('#form_transaksi').serialize(),
dataType: "JSON",
success: function(data)
{
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding data');
}
});
$('.reset').val('');
};
}
function deletebarang(id,sub_total)
{
// ajax delete data to database
$.ajax({
url : "<?= site_url('Master_rabp/deletebarang')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
Below are the codes I am using,
When I selected values from the Database, they are submitted to the database, but if I type something not in the database and I want it submitted, It does not get submitted or echoed by PHP.
Sombody Please help me.
Thank You.
<?php
//Jason File
#Include the connect.php file
include('db_connect2.php');
//get county of selected district
$query = "SELECT * FROM primary_schools ";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$customers[] = array(
'Emis_No' => $row['Emis_No'],
'District' => $row['District'],
'County' => $row['County'],
'Subcounty' => $row['Subcounty'],
'Parish' => $row['Parish'],
'School' => $row['School']
);
}
echo json_encode($customers);
?>
//Script
<script type=”text/javascript”>
$(document).ready(function () {
//start EMIS code
var customersSourcel =
{
datatype: "json",
datafields: [
{ name: 'Emis_No'},
{ name: 'District'},
{ name: 'County'},
{ name: 'Subcounty'},
{ name: 'Parish'},
{ name: 'School'}
],
url: 'includes/emis.php',
cache: false,
async: false
};
var customersAdapterl = new $.jqx.dataAdapter(customersSourcel);
$("#emis_no").jqxComboBox(
{
source: customersAdapterl,
width: 200,
height: 25,
promptText: "emis",
displayMember: 'Emis_No',
valueMember: 'Emis_No'
});
$("#emis_no").bind('select', function(event)
{
if (event.args)
{
var index = $("#emis_no").jqxComboBox('selectedIndex');
if (index != -1)
{
var record = customersAdapterl.records[index];
document.form1.district.value = record.District;
$("#county").jqxComboBox({ disabled: false});
document.form1.county.value = record.County;
$("#sub_county").jqxComboBox({ disabled: false});
document.form1.sub_county.value = record.Subcounty;
$("#parish").jqxComboBox({ disabled: false});
document.form1.parish.value = record.Parish;
$("#school").jqxComboBox({ disabled: false});
document.form1.school.value = record.School;
}
}
});
Initialize $customers array with $customers = array(); in the begining of the PHP file before you start pushing values into it with $customers[] = ...
Is there a way to add row as html to datatable? I understand that the suggested way of doing it is this:
$('#addRow').on( 'click', function () {
t.row.add( [
counter +'.1',
counter +'.2',
counter +'.3',
counter +'.4',
counter +'.5'
] ).draw( false );
counter++;
} );
But I have a complex JSON input and I want to pre process it in PHP. Is it doable or even possible?
EDIT:
So instead of doing the code above:
t.row.add(resultfromphpserverwithalltherows);
UPDATE:
JSON output
{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed"}
and sometimes:
{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed","othersubjects":[{"applied math":"90","general science":96,"world history":99,"literature":93,"pe":"96"}],"remarks":"passed"}
So I can't really define the columns because the JSON output is dynamic and that's why I want to preprocess it in PHP first.
No matter how you approach this, there's going to be some significant data-formatting required.
Best approach for what you're asking: use DataTables server-side tools.
It requires including some additional components, but will simplify the javascript down to:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
} );
...with a little tweaking, you can simplify that further:
$(function(){
var dt = new dataTableAuto();
dt.load();
});
function dataTableAuto() {
this.params = {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
};
this.load = function() {
$('#example').DataTable( this.params );
}
}
php ajax server to send raw JSON as a single row
Simply send an ajax request to php which includes the counter, then respond with a json array matching what you want to build.
Javascript snippet
counter = 0;
$.ajax({
url: '[your url]',
type: 'post',
data: {"counter":counter},
contentType: "application/json",
dataType: 'json',
success: function(response){
t.row.add(JSON.parse(response)).draw( false );
counter++;
},
});
php Snippet
$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$counter = $data['counter'];
$totalRows = 10;
for( $i = 0; $i < $totalRows; $i++) {
$result[] = $counter .".". $i;
}
header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;
DataTables pure AJAX approach
javascript
$(function(){
t = $('#example');
$.ajax({
url: '[your url]',
type: 'post',
data: {"classID":12},
contentType: "application/json",
dataType: 'json',
success: function(response){
t.DataTable( JSON.parse(response) );
},
});
});
php
$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$classID = intval($data['classID']);
$cols = array('Name', 'Position', 'Score');
foreach ( $cols as $colName ) {
$entry = new stdClass();
$entry->title = $colName;
$result['columns'][] = $entry;
}
$result = // some query [ex: get rows by class id]
foreach( $result as $row) {
$thisRow = array();
foreach ( $cols as $colName ) {
$thisRow[] = $row['$colName']
}
$result['data'][] = $thisRow;
}
header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;
This should produce an object similar to:
{
data: [
['Joseph Taylor', '22', '90']
],
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Score" }
]
}
I have a json_encode in my php script which seems to fail the Jquery side of things if the json_encode is called inside a while loop.
When i view the result in a browser window other than the page i need the result in i can see that it does actually does work.
For example:
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$data = array("id" => $id,
"title" => $title,
"success" => true
);
echo json_encode($data); // Inside the While Loop
}
and the output in the browser is:
{"id":"15","title":"Advanced Booking Examples","success":true}
{"id":"14","title":"Advanced Booking Fields","success":true}
{"id":"11","title":"Add New Driver","success":true}
{"id":"10","title":"Registering a Driver \/ Add New Vehicle","success":true}
{"id":"8","title":"Dispatch Controls","success":true}
{"id":"7","title":"Troubleshooting Driver Device Checklist","success":true}
{"id":"6","title":"Requirements Checklist","success":true}
In the jQuery response this is actually blank but if I leave the echo json_encode($data); just outside the while loop the jQuery picks up the response, however only 1 record - being the last record in the loop.
I need the jQuery to pick up all results from the loop.
Here's the JS
$.ajax({ // Send it off for prcessing
type: "POST",
dataType: 'json',
url: "includes/auto_suggest.php",
data: {
q: inputString
},
success: function (result) {
if (result.success) {
var id = result.id;
var title = result.title;
$('#auto_id').append("<input type='text' class='hideid' id='hideid_" + id + "' value='" + id + "'/>");
$('#auto_title').prepend("<p>" + title + "</p>");
}
}
});
Any ideas?
Thanks in advance
JSON needs to all be on one array or object. You need to append each row to an array, then json_encode that.
$data = array();
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$data[] = array(
"id" => $id,
"title" => $title,
"success" => true
);
}
echo json_encode($data);
Then in JavaScript, you will have an array of objects, that you can loop through.
$.ajax({ // Send it off for prcessing
type: "POST",
dataType: 'json',
url: "includes/auto_suggest.php",
data: {
q: inputString
},
success: function (result) {
$.each(result, function(){
if (this.success) {
var id = this.id;
var title = this.title;
$('#auto_id').append("<input type='text' class='hideid' id='hideid_" + id + "' value='" + id + "'/>");
$('#auto_title').prepend("<p>" + title + "</p>");
}
});
}
});
Well, you are not sending valid JSON.
Store the objects in an array and then json_encode that array after the loop.
$data = array();
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$data[] = array("id" => $id,
"title" => $title,
"success" => true
);
}
echo json_encode($data);
You then need to change your JavaScript code to properly handle an array instead of an object. Since nobody here knows what exactly you intend to do you'll have to do that on your own or provide more information.
You need to add the resulting data to an array and call json_encode once, like so:
$data = array();
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$data[] = array("id" => $id,
"title" => $title,
"success" => true
);
}
echo json_encode($data);
This will change your outputted JSON (since currently your JSON is invalid), which you now have to loop over in your jQuery callback.
The JSON that gets returned when that line is inside the loop isn't valid as a whole. It's multiple JSON strings together. You would need to split them up.
I would make an array and inside the loop add each $data to that array. Then, outside of the loop, json_encode it and echo it. This will create one JSON string to return to your javascript.
Perhaps...
$data = array();
while( WHATEVER ){
// other code
$data[] = array('id' => $id, 'title' => $title, 'success' => true);
}
echo json_encode($data);
Store all your information in one array, then encode that array.
You can't pass multiple objects like that to jQuery. Put the in array and print the array of objects when the while loop is done.
You need to encode json outside the while loop. it will return single json, which is actually correct
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$data[] = array("id" => $id,
"title" => $title,
"success" => true
);
}
echo json_encode($data);
Your JSON output is not valid. Try this complete code (EDIT):
$result = Array();
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$data = array("id" => $id,
"title" => $title,
);
$result[] = $data;
}
echo json_encode(Array('data'=>$result,'success'=>true)); // Outside the While Loop
And in your javascript code
$.ajax({ // Send it off for prcessing
type: "POST",
dataType: 'json',
url: "includes/auto_suggest.php",
data: {
q: inputString
},
success: function (results) {
if (results.success) {
for(var i in results.data) {
var result = results.data[i];
var id = result.id;
var title = result.title;
var $newfield = $("<input type='text' class='hideid' id='hideid_" + id + "' value='" + id + "'/>");
$newfield.prepend("<p>" + title + "</p>");
$('#auto_title').append($newfield);
}
}
}
});