Notice: Undefined index: draw using Datatables.net server-side - javascript

Error Message:
Notice: Undefined index: draw.
Also, my JSON response comes out wrong: {"draw":0,"recordsTotal":23,"recordsFiltered":23,"data":[]}
....draw (above) is supposed to be 1 not 0.
Code:
$(document).ready(function() {
var asc = true;
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "server.php",
"type": "POST",
},
columnDefs: [{
targets: -1,
defaultContent: '<button type="button">Delete</button>'
}],
rowGroup: {
dataSrc: 1
}
});
});
</script>
<body>
<table id="example" class="display" style="width:100%" class="table table-striped table-bordered table-hover table-condensed">
<thead class="thead-inverse">
<tr>
<th> ID </th>
<th>First Name </th>
<th>Last Name </th>
<th>Position </th>
<th>Date </th>
<th>Updated </th>
<th>Action</th>
</thead>
</tr>
<tbody>
</tbody>
</table>
</div>
<?php
$data=array();
$requestData= $_REQUEST;
$count=mysqli_query($con, "SELECT * FROM employees");
$totalData= $count->num_rows;
$totalFiltered=$totalData;
$json_data = array(
"draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval( $totalData ),
"recordsFiltered" => intval( $totalFiltered ),
"data" => $data // total data array
);
echo json_encode($json_data);
?>
</script>
<body>
<?php
$data=array();
$requestData= $_REQUEST;
$query=mysqli_query($con, "SELECT * FROM employees");
$totalData= $count->num_rows;
$totalFiltered=$totalData;
if( !empty($requestData['search']['value']) ) {
// if there is a search parameter
$sql = "SELECT first_name, last_name, position, date, updated";
$sql.=" FROM employees";
$sql.=" WHERE first_name LIKE '".$requestData['search']['value']."%' ";
// $requestData['search']['value'] contains search parameter
$sql.=" OR last_name LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR position LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR date LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR updated LIKE '".$requestData['search']['value']."%' ";
$query=mysqli_query($con, $sql);
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result without limit in the query
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." "; // $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc , $requestData['start'] contains start row number ,$requestData['length'] contains limit length.
$query=mysqli_query($con, $sql); // again run query with limit
} else {
$sql = "SELECT first_name, last_name, position, date, updated";
$sql.=" FROM employees";
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
$query=mysqli_query($con, $sql);
}
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData[] = $row["titulo"];
$nestedData[] = $row["descripcion"];
$data[] = $nestedData;
}
?>
Good chance I will not get an answer. But figured it is worth a try. I am still waiting back a response from datatables.net. Thanks.
Server.php File:
<?php
$table = 'employees';
$primaryKey = 'id'; // Table's primary key
$columns = array(
array( 'db' => 'id', 'dt' => 0 ),
array( 'db' => 'first_name', 'dt' => 1 ),
array( 'db' => 'last_name', 'dt' => 2 ),
array( 'db' => 'position', 'dt' => 3 ),
array( 'db' => 'date', 'dt' => 4 ),
array( 'db' => 'updated', 'dt' => 5 ),
);
$sql_details = array(
'user' => 'username',
'pass' => 'password',
'db' => 'database',
'host' => 'localhost'
);
require( 'ssp.class.php' );
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
?>

One of your issues, is that the variables you're trying to access aren't defined. You're trying to access your 'draw' variable, but in no place do you actually define it.
I see you attempt to access it at $requestData= $_REQUEST; in conjunction with "draw" => intval( $requestData['draw'] ) but $_REQUEST only gets the $_GET and $_POST variables of the current page. Read more here: http://php.net/manual/en/reserved.variables.request.php
You would need to do a separate request to server.php to get those values.
The reason why your draw is 0 is because intval(null) is 0. (An undefined variable is null)

Answer: Change $_get to $_post in the server.php file.
This is the response I got from datatables.net. The post above is related to this response too:
"Your server script is returning the draw value. The SSP doc indicates what your script should be doing with this parameter:
https://datatables.net/manual/server-side#Returned-data
The draw parameter increments for each draw request. This portion of the doc explains its use:
https://datatables.net/manual/server-side#Sent-parameters
The dataSrc option does not affect the draw value."
I will edit in the full answer once as we solve this completely. But this is the general answer for now...

use isset();
like below
$draw = isset($postData['draw']);
$start = isset($postData['start']);
$rowperpage = isset($postData['length']); // Rows display per page
$columnIndex = isset($postData['order'][0]['column']); // Column index
$columnName = isset($postData['columns'][$columnIndex]['data']); // Column name
$columnSortOrder = isset($postData['order'][0]['dir']); // asc or desc
$searchValue = isset($postData['search']['value']); // Search value
Notice: Undefined index: draw. will be solved

Related

Serach and ordering is not working Datatables Server Side Processing (Codeigniter)?

I'am trying to display same data using datatables server side processing at Codeigniter.I should use 'where' clause and i'am using Emran ul hadi script class.(Visit https://emranulhadi.wordpress.com/2014/06/05/join-and-extra-condition-support-at-datatables-library-ssp-class/#comment-196).
My controller script :
$sql_details = array(
'user' => 'root',
'pass' => '',
'db' => 'kreatx',
'host' => 'localhost'
);
$index = $this->uri->segment(3);
$table = 'user';
$columns = array(
array('db' => 'Name', 'dt' => 0),
array('db' => 'Lastname', 'dt' => 1),
array('db' => 'Email', 'dt' => 2),
array('db' => 'Username', 'dt' => 3),
array('db' => 'Password', 'dt' => 4)
);
$primaryKey = 'ID';
$this->load->model('employees_model');
$department = $this->employees_model->get_department($index);
require( 'SSP.php' );
$where = 'Department = '.$index.'';
echo json_encode(
SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns,
null ,$where )
);
My view script :
$('#employees').DataTable({
"responsive":true,
"processing":true,
"serverSide":true,
"searching":true,
"ordering":true,
"order":[],
"ajax":{
url:"<?php echo base_url() .
'employees/get_employees/'.$index.''; ?>",
type:"POST"
},
"columnDefs":[
{
"targets":[4],
"orderable":false,
},
],
});
Table is displaying correctly,with no errors.But search and order does'nt work.
If i try to search it just say prrocessing and show the same table.
Same problem with ordering.
Any sugesstion please ?
Thanks !
On your script you set "serverside" parameter to "true"
That means all the filtering and sorting needs to be in your php script. Every time you change the order or try to apply a filter, the dataTables javascript will send an ajax call to the php page you have listed under the ajax parameter. The ajax call will include everything you need inside of get or post variables that you can parse.
You need to write the code in php to parse the URL parameters and dynamically create a sql query that filters your database results.
I haven't done this in Codeignitor before but this is a quick example of what I would try in Laravel (note, you need to hard code your own database columns or if you're advanced then you can loop the code into an array of your database column names)
public function MyExampleJson(Request $request)
{
$len = $_GET['length'];
$start = $_GET['start'];
$select = "SELECT *,1,2 ";
$presql = " FROM entities a ";
$whereused = false;
if($_GET['search']['value']) {
$presql .= " WHERE (id LIKE '%". $_GET['search']['value']."%' ";
$presql .= " OR column01 LIKE '%". $_GET['search']['value']."%' ";
$presql .= " OR column02 LIKE '%". $_GET['search']['value']."%' ";
$presql .= " OR column03 LIKE '%". $_GET['search']['value']."%' ";
$presql .= " OR column04 LIKE '%". $_GET['search']['value']."%' ";
$presql .= ") ";
$whereused = true;
}
$orderby = "";
$columns = array('column01','column02','column03','column04');
$order = $columns[$request->input('order.0.column')];
$dir = $request->input('order.0.dir');
$columnsearcharray = $request->columns;
foreach ($columnsearcharray as $key => $value)
{
if ($value['search']['value']) {
if ($whereused) {
$presql .= " AND ";
} else {
$presql .= " WHERE ";
$whereused = true;
}
$presql .= $columns[$key] . " LIKE '%" . $value['search']['value'] . "%' ";
}
}
$orderby = "Order By " . $order . " " . $dir;
$sql = $select.$presql.$orderby." LIMIT ".$start.",".$len;
$qcount = DB::select("SELECT COUNT(a.id) c".$presql);
$count = $qcount[0]->c;
$results = DB::select($sql);
$ret = [];
foreach ($results as $row) {
$r = [];
foreach ($row as $value) {
$r[] = $value;
}
$ret[] = $r;
}
$ret['data'] = $ret;
$ret['recordsTotal'] = $count;
$ret['iTotalDisplayRecords'] = $count;
$ret['recordsFiltered'] = count($ret);
$ret['draw'] = $_GET['draw'];
echo json_encode($ret);
}

Clickable Data Table Row

I am having a data table which is fetching its data from MySQL database. In my database i am having a column named as "location" which is a link to some audio file. All the rows in the database are having their respective links to their audio files.What i want is that
When i click on any row of the data table the browser should automatically get redirected to the link of their respective audio files.
The Current link that is stored in the database is for local IP. i want to change the link to my public IP before the user is redirected since the local IP won't work on remote server. Below is my code:
data table.php
<?php
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "vici";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* Database connection end */
// storing request (ie, get/post) global array to a variable
$requestData= $_REQUEST;
$columns = array(
// datatable column index => database column name
0 =>'recording_id',
1 => 'call_date',
2=> 'location',
3=> 'Agent',
4=> 'phone'
);
// getting total number records without any search
$sql = "SELECT recording_id, call_date, location,agent,phone";
$sql.=" FROM goautodial_recordings_view";
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
$sql = "SELECT recording_id, call_date, location,agent,phone";
$sql.=" FROM goautodial_recordings_view WHERE 1=1";
if( !empty($requestData['search']['value']) ) { // if there is a search parameter, $requestData['search']['value'] contains search parameter
$sql.=" AND ( recording_id LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR call_date LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR agent LIKE '".$requestData['search']['value']."%' )";
}
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result.
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
/* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc */
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData[] = $row["recording_id"];
$nestedData[] = $row["call_date"];
$nestedData[] = $row["location"];
$nestedData[] = $row["agent"];
$nestedData[] = $row["phone"];
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval( $totalData ), // total number of records
"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
index.php
<!DOCTYPE html>
<html>
<title>GO VOIP</title>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css">
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" >
$(document).ready(function() {
var dataTable = $('#employee-grid').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"employee-grid-data.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display","none");
}
}
} );
$('.dataTable').on('click', 'tbody td', function() {
//get textContent of the TD
alert('TD cell textContent : ', this.textContent)
//get the value of the TD using the API
('value by API : ', table.cell({ row: this.parentNode.rowIndex, column : this.cellIndex }).data());
})
} );
</script>
<style>
div.container {
margin: 0 auto;
max-width:760px;
}
div.header {
margin: 100px auto;
line-height:30px;
max-width:760px;
}
body {
background: #f7f7f7;
color: #333;
font: 90%/1.45em "Helvetica Neue",HelveticaNeue,Verdana,Arial,Helvetica,sans-serif;
}
</style>
</head>
<body>
<div class="header"><h1>DataTable demo (Server side) in Php,Mysql and Ajax </h1></div>
<div class="container">
<table id="employee-grid" cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
<thead>
<tr>
<th>Recording ID</th>
<th>Call date</th>
<th>Location</th>
<th>Agent</th>
<th>Phone</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
Below is the Screenshot:
method 1 :
change in SQL query (only where you get rows not count)
$sql = "SELECT recording_id, call_date, CONCAT('get song'),agent,phone";
note : if you have some field in mysql like song_name then you display in anchor tag
$sql = "SELECT recording_id, call_date, CONCAT('',song_name,''),agent,phone";
OR
method 2 :
change in PHP while loop
//replace from
$nestedData[] = $row["location"];
to
$nestedData[] = 'get song';
You can do it in simple php with eco like:
echo 'Name of the song';
If you click on it it will redirect you to the file.
$(document).ready(function() {
$.ajax({
type: "POST",
url: "employee-grid-data.php",
success: function(data){
data = JSON.parse(data);
/*Here you will get the data
Loop through the data and append to dataTable*/
$('#employee-grid').DataTable();
},
error : function() { // error handling
$(".employee-grid-error").html("");
$("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display", "none");
}
});
Use ajax to get JSON data from the server and manually add it to the HTML table, finally initialize datatable.

How to work with array JSON in php?

I'm a JavaScript Programmer and has a project with PHP.
I'm having trouble with working JSON with PHP.
This is my JSON
{
"orders":[
{
"name":"#1002"
},
{
"name":"#1001"
}
]
}
I need to get each name and echo them, I tried the following code $myarray = json_decode($order, true) but it returns me this error.
Warning: json_decode() expects parameter 1 to be string, array given in
How can i convert the json from array to string? or am i doing it wrong.
config.php
<?php
$con = mysql_connect('localhost','root','');
mysql_select_db('db_school',$con);
$sql = "SELECT * FROM userlogin";
$result = mysql_query($sql,$con);
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] =array(
'id'=>$row['id'],
'username'=>$row['username'],
'userpass'=>$row['userpass'],
);
}
echo json_encode(array('data'=>$data));
?>
view.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table id="tbl" border="1">
<thead><tr>
<th>Id</th>
<th>Username</th>
<th>Password</th>
</tr></thead>
<tbody></tbody>
</table>
<script type="text/javascript">
$.ajax({
url: 'config.php',
}).done(function(res) {
var res_data = JSON.parse(res),table='';
$.each(res_data.data,function(index, el) {
console.log(el.id,' ', el.username,' ',el.userpass);
table+='<tr>';
table+='<td>'+el.id+'</td>';
table+='<td>'+el.username+'</td>';
table+='<td>'+el.userpass+'</td>';
table+='</tr>';
});
$('#tbl').html(table);
});
</script>
Demo:
Simply save the json response on a variable. And then do json_decode
$orders = '{
"orders":[
{
"name":"#1002"
},
{
"name":"#1001"
}
]
}';
$myarray = json_decode($orders, true);
Now performing print_r will yield result like
echo '<pre>';
print_r($myarray);
Result
Array
(
[orders] => Array
(
[0] => Array
(
[name] => #1002
)
[1] => Array
(
[name] => #1001
)
)
)
EDIT :
In order to get only name values simply run a foreach
$result = [];
foreach($myarray['orders'] as $value) {
$result[] = $value['name'];
}
Now printing $result you will get
Array
(
[0] => #1002
[1] => #1001
)

Checkbox not getting right order

I have these checkboxes used for identifying (if checked) should email the respective client, it's supposed to be pre-checked.
But when it is pre-checked, and then when I unchecked one checkbox e.g multipayment_email[1], when submitted to PHP the one getting unset is the last index multipayment_email[4].
list_payments.php:
<form method="POST">
<?php while($row = mysqli_fetch_array($selectQuery) { ?>
<input type="text" name="multipayment_name[]" required/>
<input type="checkbox" name="multipayment_email[]" checked />
<?php } ?>
</form>
SUBMIT_payment.php:
$names = $_POST['multipayment_name'];
$emails = $_POST['multipayment_email'];
foreach ($names as $key => $name)
{
$email = isset($emails[$key]) ? 1:0;
$query = "INSERT INTO payments() VALUES (NULL, '$name', $email)";
$response['message'] .= $query."<br/>";
}
die(json_encode($response));
So when I submit the form this is the output (given that I unchecked the 2nd index out of 5 check boxes):
"INSERT INTO payments() VALUES (NULL, '1 waw', 1)"
"INSERT INTO payments() VALUES (NULL, '2 wew', 1)"
"INSERT INTO payments() VALUES (NULL, '3 wiw', 1)"
"INSERT INTO payments() VALUES (NULL, '4 wow', 1)"
"INSERT INTO payments() VALUES (NULL, '5 wuw', 0)"
It should be
"INSERT INTO payments() VALUES (NULL, '2 wew', 0)"
any enlightenment?
Try this:
<form method="POST">
<?php $idx = 0; ?>
<?php while($row = mysqli_fetch_array($selectQuery)): ?>
<input type="text" name="rows[<?php echo $i; ?>][name]" required/>
<input type="checkbox" name="rows[<?php echo $i; ?>][email]" checked />
<?php ++$idx; ?>
<?php endwhile; ?>
</form>
And so if third checkbox is unchecked, you will obtain the $_POST data in this format:
array(
'rows' => array(
array(
'name' => 'the value of name 1',
'email' => 'on'
),
array(
'name' => 'the value of name 2',
'email' => 'on'
),
array(
'name' => 'the value of name 3'
)
)
)
Checkboxes that doesn't check will have the field unset and not being posted, and from there you can easily do an isset check to know if it's checked or not.
$rows = $_POST['rows'];
foreach ($rows as $row) {
$email = isset($row['email') ? 1 : 0;
$name = $row['name'];
$query = "INSERT INTO payments() VALUES (NULL, '$name', $email)";
$response['message'] .= $query."<br/>";
}
But DO WARNED that this code is susceptible to sql injection. Since this is out of the scope of this question let us not dive into that here :)
All Inputs need to have different names.
Now there are a faw Inputs with two names multipayment_name[] and multipayment_email[]
The last one is not being unchecked, this line of code is giving you the undesired result.
$email = isset($emails[$key]) ? 1:0;
When you uncheck the checkbox, it won't be submitted to the server. dump your submitted checkboxes array i think you will get it )

How to make functions to return a json string on calling them in php?

I made the following script but I want that each script should echo the json_encode array only when I call the function. When I tried defining the function, and then calling it, it displayed nothing. It is working if the scripts are not made in the functions. How do I make different functions and then call different functions according to my usage?
<?php
ini_set('display_errors', '0');
error_reporting(0);
require_once("include/db.php");
date_default_timezone_set('Asia/Kolkata');
$regno ='14ASDFJ234';
$password = '0';
$name = 'EASPORTS';
$priority = 0;
//fetch priority
$query = "SELECT priority FROM users WHERE regno='{$regno}' AND pass='{$password}' LIMIT 1";
$res = mysql_query($query, $conn) or die(mysql_error());
$found = mysql_fetch_array($res);
if($found)
{
$priority=$found['priority'];
}
//echo $priority;
echo 'news feed : <br> '
$sql = "SELECT * FROM newsfeed";
$result = mysql_query($sql,$conn) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$details[] = array(
'name' => $row['name'],
'feed' => $row['feed']
);
}
echo json_encode($details);
// announcement details...
echo "<br> Announcement details: <br>";
$sql1 = "SELECT * FROM announcements WHERE name = '$name'";
$result1 = mysql_query($sql1,$conn) or die(mysql_error());
while ($row1 = mysql_fetch_array($result1)) {
$details1[] = array(
'name' => $row1['name'],
'pname' => $row1['pname'],
'date' => $row1['date'],
'time' => $row1['time'],
'status' => $row1['status']
);
}
echo json_encode($details1);
//events script...
?>
You should do like this
public function somefunction()
{
$query = "SELECT priority FROM users WHERE regno='{$regno}' AND pass='{$password}' LIMIT 1";
$res = mysql_query($query, $conn) or die(mysql_error());
$found = mysql_fetch_array($res);
if($found)
{
$priority=$found['priority'];
}
//echo $priority;
echo 'news feed : <br> '
$sql="SELECT * FROM newsfeed";
$result=mysql_query($sql,$conn) or die(mysql_error());
while ($row=mysql_fetch_array($result)) {
$details[] = array(
'name' => $row['name'],
'feed' => $row['feed']
);
}
echo json_encode($details);
}
now when you call somefunction() you will get json encoded array as result

Categories

Resources