Invalid json response in jquery datatable - php

I have tried jquery datatables for the first time. After referring the manual etc I was able to write the program below, but I am constantly getting an error stating that the json response is invalid.
model file:
public function inbox($data)
{
$con = mysqli_connect("localhost", "root", "","mailman");
$sentFromEmail = $data['sentFromEmail'];
$querySender = "SELECT userId FROM users WHERE userEmail= '$sentFromEmail'";
$resSender = mysqli_query($con, $querySender);
$rowSender = mysqli_fetch_assoc($resSender);
$columnSender = $rowSender["userId"];
$querySender = "SELECT mailId,mailSender,mailSubject,mailContent, mailSendDate FROM mails WHERE mailReceiver = '$columnSender'";
$resSender = mysqli_query($con, $querySender);
$rowSender = mysqli_fetch_assoc($resSender);
$myMail = array();
$test = array();
while($row = mysqli_fetch_array($resSender))
{
$senderId = $row['mailSender'];
$querySenderName = "SELECT userName FROM users WHERE userId= '$senderId'";
$resSenderName = mysqli_query($con, $querySenderName);
$rowSenderName = mysqli_fetch_assoc($resSenderName);
$columnSenderName = $rowSenderName["userName"];
$test[] = $row;
$myMail[] = array(
'mailId' => $row['mailId'],
'mailSender' => $columnSenderName,
'mailSubject' => $row['mailContent'],
'mailContent' => $row['mailSubject'],
'mailSendDate' => $row['mailSendDate']
);
// $myMailData = json_encode($test);
// echo $myMailData;
}
return $test;
}
controller:
public function index()
{
//$userLoginData = $this->session->userdata('user_login');
$data = array(
'sentFromEmail' => $this->session->userdata['user_login']['loginEmail'] ,
);
//load the method of model
$mailBoxData = array();
$mailBoxData['mailBoxData'] = $this->mail_receive->inbox($data);
$jsonData = json_encode($mailBoxData);
echo $jsonData;
$this->load->view('inbox', $mailBoxData);
}
view file:
<script>
$(document).ready(function() {
$('#inbox').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url" : "http://localhost/codeigniter/index.php/Inbox_redirect/index",
"type" : "POST",
"dataSrc": ""
},
"columns" : [
{"data" : "mailId"},
{"data" : "mailSender"},
{"data" : "mailSubject"},
{"data" : "mailContent"},
{"data" : "mailSendDate"} ]
} );
} );
</script>
<table class="table table-hover table-striped" id="inbox" name="inbox">
<thead>
<th>ID</th>
<th>Sent By:</th>
<th>Time</th>
<th>Subject</th>
<th>Message</th>
</thead>
<div class="container">
<tbody>
</tbody>
</div>
</table>
How do I rectify the error?
the json response that getting recorded is
[{"mailId":"13","mailSender":"nikita","mailSubject":"testing","mailContent":"njcndncvjdvnfjvnfvnfjvnjkfnvkfnbkfkbnfdbteb","mailSendDate":"2016-11-16 15:04:20"},{"mailId":"14","mailSender":"nikita","mailSubject":"testing","mailContent":"njcndncvjdvnfjvnfvnfjvnjkfnvkfnbkfkbnfdbteb","mailSendDate":"2016-11-16 15:23:02"},{"mailId":"17","mailSender":"nikita","mailSubject":"wygdyegfhfbvhrvf","mailContent":"ghfgregughuthgujbhjhykhytj","mailSendDate":"2016-11-17 12:55:20"},{"mailId":"21","mailSender":"jyotsna","mailSubject":"hi there","mailContent":"hello, how are you?","mailSendDate":"2016-11-18 14:50:56"}]

Try to add "dataType" inside:
"ajax": {
"url" : "http://localhost/codeigniter/index.php/Inbox_redirect/index",
"type" : "POST",
"dataSrc": ""
}
like this:
"ajax": {
"url" : "http://localhost/codeigniter/index.php/Inbox_redirect/index",
"type" : "POST",
"dataType": "json", // The type of data that you're expecting back from the server.
"dataSrc": ""
}
If this won't work, you can still try to parse the result which you get like this: JSON.parse('your JSON string');. The JSON string which you send from PHP, made with the json_encode() method.

Related

Send POST parameters to PHP in ajax call of jQuery datatable

I want to make a jQuery function in where, getting a value of an input, send it to a PHP file to make a query in mysql and populate a datatable with the information received.
Another problem I have is that the table is initialized when the user is logged in and I don't know if that can obstruct the function I want to do.
This the table:
Table and button
This is where I initialize it:
$.fn.dataTable.ext.errMode = 'none';
var table = $('#m3_sem').DataTable( {
"ajax": "dist/ajax/prueba_m3_sem.php",
"paging": false,
"ordering": false,
"info": false,
"searching": false,
"columns": [
{ "data": "resistencia" },
{ "data": "res1" },
{ "data": "res2" },
{ "data": "res3" },
{ "data": "res4" },
{ "data": "res5" },
{ "data": "res6" },
{ "data": "total" }
],
"order": [[0, 'asc']],
"pagingType": "full_numbers",
"language": {
"sSearch" : "Buscar:",
"lengthMenu": "Mostrando _MENU_ registros por pagina",
"zeroRecords": "No hay pedidos pendientes",
"info": "Mostrando pagina _PAGE_ de _PAGES_",
"infoEmpty": "Sin registros",
"infoFiltered": "(Filtrados de _MAX_ registros totales)",
"paginate" : {
"first" : "Primera pagina",
"previous" : "Anterior",
"next" : "Siguiente",
"last" : "Ultima pagina"
}
}
});
} );
And this is the PHP file "prueba_m3_sem.php", it generates the JSON I use to populate the table:
$sql = "SELECT DISTINCT resistencia ";
$sql.= "FROM registros ORDER BY resistencia";
$query=mysqli_query($conexion, $sql) or die("ajax-grid-data.php: get PO");
$data = array();
while( $row=mysqli_fetch_array($query) ) {
$sumtot = 0;
$nestedData=array();
$nestedData["resistencia"] = $row["resistencia"];
$sqld = "SELECT DISTINCT(fecha_entrega) FROM registros where sem_entrega = ".date("W")." and YEAR(fecha_entrega) = ".date("Y")." ORDER BY fecha_entrega";
$queryd=mysqli_query($conexion, $sqld) or die("ajax-grid-data.php: get PO");
$count = 0;
$tot = 0;
while( $rowd=mysqli_fetch_array($queryd) ) {
$count++;
$m3tot = 0;
$sqlm = "SELECT m3 FROM registros WHERE fecha_entrega = '".$rowd["fecha_entrega"]."' AND resistencia =".$row["resistencia"]."";
$querym=mysqli_query($conexion, $sqlm) or die("ajax-grid-data.php: get PO");
while( $rowm=mysqli_fetch_array($querym) ) {
if (empty($rowm['m3'])){
$m3 = 0;
}else{
$m3 = $rowm["m3"];
}
$m3tot = $m3tot + $m3;
}
$tot = $tot + $m3tot;
$nestedData["res".$count] = $m3tot;
$sumtot = $sumtot + $m3tot;
}
$nestedData["total"] = "<b>".$sumtot."</b>";
$data[] = $nestedData;
}
$sqld2 = "SELECT DISTINCT(fecha_entrega) as fecha FROM registros where sem_entrega = ".date("W")." and YEAR(fecha_entrega) = ".date("Y")." ORDER BY fecha_entrega";
//echo $sqld;
$queryd2=mysqli_query($conexion, $sqld2) or die("ajax-grid-data.php: get PO");
$totm3 = 0;
$nestedData["resistencia"] = "<b>Total</b>";
$count = 0;
while( $rowd2=mysqli_fetch_array($queryd2) ) {
//echo $rowd["fecha"]."</br>";
$sqltot = "SELECT SUM(m3) AS m3 from registros WHERE fecha_entrega ='".$rowd2["fecha"]."'";
$querytot=mysqli_query($conexion, $sqltot) or die("ajax-grid-data.php: get PO");
while( $rowtot=mysqli_fetch_array($querytot) ){
$count ++;
//echo $rowtot["m3"]."</br>"
$nestedData["res".$count] = "<b>".$rowtot["m3"]."</b>";
$totm3 = $totm3 + $rowtot["m3"];
}
}
$nestedData["total"] = "<b>".$totm3."</b>";
$data[] = $nestedData;
$json_data = array("data" => $data);
echo json_encode($json_data);
I've seen some code examples and the datatable documentation but I just can't find something that fits in the function I need or I just don't understand it very well.
Also, as you can see, English is not my native language. I hope and you can forgive my misspellings.
In advance thanks a lot for your response.
what I understand is that you want to display some results in your table after you submit some search value? if thats the case here is a little example I did using a employees sample db with mysql:
the html:
<div class="container">
<input type="text" name="txtName" id="txtName" value="">
<button type="btn btn-default" name="button" id="btnSearch">Search</button>
</div>
<div class="container" id="tblResult" style="display:none;">
<div class="row">
<div class="col-sm-6">
<table id="example" class="table table-responsive" style="width:100%">
<thead>
<tr>
<th>Cliente</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Device Id.</th>
<th>Client id</th>
<th>Accion</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Cliente</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Device Id.</th>
<th>Client id</th>
<th>Accion</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
I use an input to search employees by a name parameter in this example so if you want to filter by a date it would not be that different.
the javascript:
$(document).ready(function(){
// click event to call the datatable request
$('#btnSearch').on('click', (event) => {
let search = $('#txtName').val();// get the input value
if (search != "") {// validate that the value is not empty
//assing the datatable call to a variable
let example = $('#example').DataTable({
"destroy": true,
"responsive":{//this is usefull if you want to use a full responsive datatable just add the responsive css from dataTables.net
"details": {
renderer: function ( api, rowIdx, columns ) {
var data = $.map( columns, function ( col, i ) {
return col.hidden ?
'<tr data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
'<td>'+col.title+':'+'</td> '+
'<td>'+col.data+'</td>'+
'</tr>' :
'';
} ).join('');
return data ?$('<table/>').append( data ) :false;
}
}
},
"autoWidth": false,//
"ajax": {
"url": 'request.php',
"method": 'POST',
data:{action:"SLC",name:search}//parameter to search and the action to perform
},
"columns": [
{"data": "emp_no"},
{"data": "first_name"},
{"data": "last_name"},
{"data": "gender"},
{"data": "salary"},
{"data": "title"}
],
"language":{"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},//load all dataTables default values in spanish
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
}
]
});//fin obtener tabla
example.on( 'xhr', function ( e, settings, json ) {// check is the response is not null and show the table
if (json != null) {
$('#tblResult').css("display","");
}
} );
}
});
}); //end ready
As you can see I call the dataTable method until a search is performed also I display the Table if the response is not empty.
the php:
<?php
$host = '127.0.0.1';
$db = 'employees';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$pdo = "";
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
// a fucntion that display the employees by our search value
function getEmployeesBySearch($conn,$order,$name) {
$sql = "SELECT e.emp_no,e.first_name,e.last_name,e.gender, gs.salary, gt.title
FROM employees e
inner join (
SELECT s.emp_no,MAX(s.salary) AS salary
FROM salaries s
GROUP by s.emp_no
) as gs on e.emp_no = gs.emp_no
inner join (
SELECT t.emp_no ,t.title ,MAX(t.from_date) as from_date
FROM titles t
WHERE t.to_date = '9999-01-01'
GROUP BY t.emp_no,t.title
) gt on e.emp_no = gt.emp_no
WHERE gt.title = 'Senior Engineer'
AND e.emp_no BETWEEN 10001 and 11819";
//use bind parameters and prepared statement to do the search and prevent sql injection
if ($name != "") {
$sql .= " AND e.first_name like CONCAT( '%', :name, '%')";
}
if ($order == "DESC") {
$sql .= " ORDER BY gs.salary DESC";
}else {
$sql .= " ORDER BY gs.salary ASC";
}
$json= array();
$stmt = $conn->prepare($sql);
if ($name != "") {
$stmt->bindParam(':name', $name, PDO::PARAM_STR, 100);
}
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$rows = $stmt->fetchAll();
//store the data inside an array
foreach ($rows as $row) {
$tempArray = array(
'emp_no'=>$row["emp_no"],
'first_name'=>$row['first_name'] ,
'last_name'=>$row['last_name'],
'gender'=>$row['gender'],
'salary'=>$row['salary'],
'title'=>$row['title']
);
//json encode the array and send the response back
$json["data"][] = $tempArray;
}
echo json_encode($json);
}
if (isset($_POST["action"])) {
// we set the variables here, since you will add another stuff later I decided a switch to run a specific case with the action the user send
$action = $_POST["action"];
$order = (isset($_POST["order"]) ? $_POST["order"] : "");
$name = (isset($_POST["name"]) ? $_POST["name"] : "");
switch ($action) {
case 'SLC':
getEmployeesBySearch($pdo,$order,$name);
break;
}
}
?>
I use a simple connection here and a function that load the results from my db to send them back as a json rsponse also try to use prepared statements in your querys and bind parameters like the example
Hope it helps =)

PHP with DataTables gives an Invalid JSON response due to quotes

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));

Datatables server side processing with using Code Igniter

I'm building a forum using Code Igniter framework. I'm trying to implement Datatables server side processing. I know how to use datatables and JQuery for actions such as sorting and searching, but my database table has the potential to grow to thousands and pulling all the rows at once will not make users very happy, so I'm trying to combine both server side (Code Igniter) and client side (AJAX) processing in order to use limits and offsets. So I dug into the web and found an awesome tutorial. This is what I have:
Model: Posts_model.php
<?php
var $table = 'general_posts';
var $column_order = array(null, 'title','body','username','time','category'); //set column field database for datatable orderable
var $column_search = array('title','body','username','time','category'); //set column field database for datatable searchable
var $order = array('id' => 'desc'); // default descending order
private function get_posts_query() {
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item)
{
if($_POST['search']['value'])
{
if($i===0) // first loop
{
$this->db->group_start();
$this->db->like($item, $_POST['search']['value']);
} else {
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end();
}
$i++;
}
if(isset($_POST['order'])) {
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
} else if(isset($this->order)) {
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_gen_posts($category) {
$this->get_posts_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$this->db->where(array('category' => $category, 'display' => 'true'));
$query = $this->db->get();
return $query->result();
}
function count_filtered_gen_posts($category) {
$this->get_posts_query();
$this->db->where(array('category' => $category, 'display' => 'true'));
$query = $this->db->get();
return $query->num_rows();
}
public function count_all($category) {
$this->db->where(array('category' => $category, 'display' => 'true'));
$this->db->from($this->table);
return $this->db->count_all_results();
}
} ?>
Controller: Posts.php
<?php
public function __construct() {
parent::__construct();
$this->load->model('posts_model','general_posts');
}
public function posts($category) {
$data['category'] = $category;
$this->load->view('posts', $data);
}
public function posts_ajax($category)
{
$list = $this->general_posts->get_gen_posts($category);
$data = array();
foreach ($list as $post) {
$row = array();
$row[] = $post->title;
$row[] = $post->body;
$row[] = $post->category;
$row[] = $post->poster;
$row[] = $post->time;
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->general_posts->count_all($category),
"recordsFiltered" => $this->general_posts->count_filtered_gen_posts($category),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
} ?>
View: posts.php
<table id="table" class="table table-no-border" cellspacing="0" width="100%" style="text-align: left">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
var table;
$(document).ready(function() {
//datatables
table = $('#table').DataTable({
"paging": true,
"pageLength" : 10,
"lengthChange": true,
"searching": true,
"info": false,
"autoWidth": true,
"ordering": false,
"stateSave": true,
"processing": true,
"serverSide": true,
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo base_url('posts/posts_ajax/'.$category)?>",
"dataType": "json",
"type": "POST",
"data":{ '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>' }
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ 0 ], //first column / numbering column
"orderable": false, //set not orderable
},
],
});
});
</script>
So far, everything works as expected, but it does not entirely suit my needs. Look at these lines:
foreach ($list as $post) {
$row = array();
$row[] = $post->title;
$row[] = $post->body;
$row[] = $post->category;
$row[] = $post->poster;
$row[] = $post->time;
$data[] = $row;
}
I'd like the results of each row to display in ONE COLUMN, not in 5 colums. This is because I intend to use Bootstrap panel to display the result of each row, and customise it to suit my needs.
I want something like this for each result:
Post Title: bla bla bla
The body goes here
Posted in: category name
Posted by: name of poster
Time: 9th Sep, 2017 at 10: 30PM
I would like to control how each field is displayed, with stylings and formatings, such as converting the time field into something more human-readable (eg 9th Sep, 2017 at 10: 30PM). The problem is, since the loop is created inside the controller (rather than in view, which I'm used to), I do not know how to go about doing this. I know if I can get the loop between the table body tags ( here ), I can do what I want, but I don't think AJAX will appreciate it if I did (I tried it, 'he' didn't). This is my first dabble into AJAX.
EDIT: I am wondering if there is a way to use the contents of the post_ajax function inside view so that I can put the foreach loop inside the body tag of table.
So I need help. Please help! Sorry it's so long...
Follow the stapes And Get Result
Step 1 : - on view side paste below code
<table id="table_lists" class="table table-bordered table-hover table-striped datatable ">
<thead>
<tr>
<th>No</th>
<th>Date</th>
<th>Day</th>
<th>Holiday</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="javascript">
var t = $('#table_lists').DataTable({
"processing": true,
"serverSide": true,
"ordering": false,
"ajax": {
"url": "<?php echo admin_url('employee/lists'); ?>",
"type": "POST",
},
"columns": [
{ "data": "no" },
{ "data": "date" },
{ "data": "day" },
{ "data": "holiday" },
{ "data": "action"},
],
});
</script>
Step 2: - In Controller create function like these
public function lists(){
$json_data = $this->holiday->get_list_table();
echo json_encode($json_data);
}
Step 3: - Paste Below code in model
public function get_list_table()
{
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
$start = $params['start'];
$where = $sqlTot = $sqlRec = "";
if( !empty($params['search']['value']) ) {
$where .=" AND ";
$where .=" ( ";
$where .=" name LIKE '%".$params['search']['value']."%' ";
$where .=" OR DATE_FORMAT(date, \"%d-%m-%Y\") LIKE '%".$params['search']['value']."%' ";
$where .=" OR DAYNAME(date) LIKE '%".$params['search']['value']."%' ";
$where .=" )";
}
$sql = "SELECT *
FROM {$this->tbl_holiday}
WHERE 1 = 1 {$where}
ORDER BY date ASC";
$sqlTot .= $sql;
$sqlRec .= $sql;
$sqlRec .= " LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = $this->db->query($sqlTot);
$totalRecords = $queryTot->num_rows();
$queryRecords = $this->db->query($sqlRec);
$results = $queryRecords->result();
$i = ($start + 1);
if(!empty($results)) {
foreach ($results as $result) {
$actions = '<a href="javascript:void(0);" onclick="javascript: editHoliday('.$result->id.');" class="btn btn-info btn-sm">
<i class="fa fa-edit"></i>
</a>
<a href="javascript:void(0);" title="Delete" data-toggle="modal" data-target="#confirm-delete" class="btn btn-danger btn-sm" data-href="'.admin_url('holiday/delete/'.$result->id).'">
<i class="fa fa-trash"></i>
</a>';
$data[] = array(
'no' => $i,
'date' => date('d-m-Y', strtotime($result->date)),
'day' => date('l', strtotime($result->date)),
'holiday' => $result->name,
'action' => $actions,
);
$i++;
}
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
return $json_data;
}

Making a hyperlink of each of the rows in data-grid table

I have a script that fills a data-grid table. I want to make a hyperlink of each of the rows that gets displayed.
The hyperlinks should look like <a href"index.php?id=(id of the row)">
How can I do that with my current script.
Here is my script:
<?php
// initilize all variable
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
//define index of column
$columns = array(
0 => 'id',
1 => 'name',
);
$where = $sqlTot = $sqlRec = "";
// check search value exist
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" name LIKE '".$params['search']['value']."%'";
}
// getting total number records without any search
$sql = "SELECT id, name FROM `customers`";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
$sqlRec .= " ORDER BY ". $columns[$params['order'][0]['column']]." ".$params['order'][0]['dir']." LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch customers data");
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
Edit 1:
Here I am displaying the data:
<table id="employee_grid" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$( document ).ready(function() {
$('#employee_grid').DataTable({
"bProcessing": true,
"serverSide": true,
"ajax":{
url :"get.php", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function(){
$("#employee_grid_processing").css("display","none");
}
}
});
});
</script>
I fixed it by changing the JavaScript.
<script type="text/javascript">
$( document ).ready(function() {
$('#employee_grid').DataTable({
"bprocessing": true,
"serverSide": true,
"ajax": {
"url": "post1.php",
"type": "POST",
"error": function(){
$("#employee_grid_processing").css("display","none");
}
},
"columnDefs": [ {
"targets": 0,
"render": function ( data, type, full, meta ) {
return 'Link';
}
}
]
});
});
</script>
This code will replace the first column with the text Link and the original result of the first column will be used in the Hyperlink.
I think you have to write a custom mRender to get this link. and add an extra
<th>Link</th> on your table header
$( document ).ready(function() {
$('#employee_grid').DataTable({
"bprocessing": true,
"serverSide": true,
"ajax": {
"url": "get.php",
"type": "POST",
"error": function(){
$("#employee_grid_processing").css("display","none");
}
},
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "id", "render": function ( data ) {
return 'Link';
}
}
]
});
});
PS please remove my old suggestion from your code.

Ajax calls resulting in an error[object Object]

I am getting an error[object Object] while trying to pass a value through ajax calls. I am using jquery selector to get value of checkbox. And trying to pass it through ajax so that I can get only the checkbox value that I have selected. But getting an error. Thanks.
Here is my code:
dashboard.php
if($param['aktion'] == 'save-widget-vehicle')
{
$page['register-fahrzeuge'] = array(
1 => array( 'Fahrzeug','aktiv',$page['script'],''),
0 => array( 'Edit-Fahrzeug','enabled',$page['script'],'',''),
);
$opts = !empty($param['filterOpts']) ? $param['filterOpts'] : array();
$tmp = array();
foreach ($opts as $opt) {
$tmp[] = '"'.$opt.'"';
}
$query =
'SELECT Fahrzeuge.dsnr,name
FROM Fahrzeuge
INNER JOIN ohne_fahrzeuge ON Fahrzeuge.dsnr = ohne_fahrzeuge.dsnr
WHERE Fahrzeuge.name IN ('.implode(",", $tmp).')';
$result = mysql_query($query, $myConnection);
$data = array();
$html = '<table width="538" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>
<div>'.CreateRegister($page['register-news']).'</div>
'.CreateMessage().'
<div class="cont-liste-verlauf register"> ';
while($row = mysql_fetch_array($result)){
//$news_result = $fahrzeuge['name'];
$html .= '<table id="fahrzeuge">
<tr>
<td>
'. $data[] = $row .'
</td>
</tr> ';
}
$html .= '</table>
</div>
</td>
</tr>
</table>';
$return = array(
'status' => 1,
'html' => $html
);
echo json_encode($return);
die();
$param['aktion'] = 'get-widget-vehicle';
}
dashboard.js
function getFahrzeuge() {
var opts = [];
$("input[type=checkbox]").each(function () {
if (this.checked) {
opts.push($(this).attr("id"));
}
});
return opts;
}
function saveFahrzeugeWidget(opts){
if(!opts || !opts.length){
opts = allFahrzeuge;
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts, 'aktion' : 'save-widget-vehicle'},
success: function(data){
// $('#fahrzeuge').html(makeTable(records));
$('#fahrzeuge').html(data.html);
},
error: function(data){
alert('error' + data);
}
});
}
$('#fahrzeuge .butt-rahmen').live('click', function(){
if($(this).attr('id') == 'submitId')
var opts = getFahrzeuge();
saveFahrzeugeWidget(opts);
});
var allFahrzeuge = [];
$("input[type=checkbox]").each(function(){
allFahrzeuge.push($(this)[0].id)
})

Categories