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.
Related
i have a table 'class' with thier fee structure. i want to show fee amount if a particular class is selected by user.
i'm able to fetch only one value from database want ot show multiple value..
here is my db table:
here are my codes:-
fetch.js
$('#class').click(function(){
$.getJSON(
'fetch2.php',
'class=' + $('#class').val(),
function(result){
$('#tution_fee').empty();
$.each(result.result, function(){
$('#tution_fee').append('<option>'+this['tution_fee']+'</option>');
});
}
);
});
fetch.php
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','bethel');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$class = $_GET['class'];
$sql = "SELECT tution_fee FROM class WHERE class='$class'";
$res = mysqli_query($con,$sql);
$result = array();
while ($row = mysqli_fetch_array($res)) {
array_push($result,
array('tution_fee'=>$row[0])
);
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
first one is fetch.js and second fetch.php
here you can see the JS code that one value can be fetched from database but i want to fetch multiple value.
please help
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
Is there a way to count the duplicate data from mysql and
display it to a bar chart, Im trying to make a attendance report
using morris bar chart.
here my sample code:
<html >
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
</head>
<body>
<div id="chart"></div>
</body>
</html>
here is my php code:
<?php
$connect = mysqli_connect("localhost", "root", "", "sa");
$query = "SELECT year, count(*) as course FROM test group by year,course order by year ASC ";
$result = mysqli_query($connect, $query);
$chart_data = '';
while($row = mysqli_fetch_array($result))
{
$chart_data .= "{ year:'".$row["year"]."', course:".$row["course"]."}, ";
}
$chart_data = substr($chart_data, 0, -2);
?>
and this is my javascript:
<script>
Morris.Bar({
element : 'chart',
data:[<?php echo $chart_data; ?>],
xkey:'year',
ykeys:['course','course','course','course','course'],
labels:['BSIT','BSHRM','BSCS','BSTM','ABCOMM'],
hideHover:'auto',
xLabelAngle: '60',
verticalGrid: true,
resize:true,
barColors: ['red','blue','green','yellow','black'],
gridTextSize: 12
});
</script>
this is my database:
UPDATED: and this is my output so far:
as you can see in my output all courses have same value for example
the two 2018-07-12 the output should be based on my database is for BSIT = 3
the rest is zero value same with the other 2018-07-12 the output should be BSHRM =1 and the rest is zero value, is there a way to achieve that?, Hope you can help me.
You have two problems with your query:
First, the alias COUNT(*) AS course reuses the column name as the alias. You need to give it a different name.
Second, you left course out of the grouping, so you're combining the counts of all courses in your results.
It should be:
$query = "SELECT year , course , count(*) as count FROM test group by year, course order by year ASC ";
Each course will then be in a different row of the results, you'll need to regroup when you process the results.
You also shouldn't create JSON by concatenating strings. Put the results in an array and use json_encode().
$results = array();
while ($row = mysqli_fetch_assoc($result)) {
$results[$row['year']]['year'] = $row['year'];
$results[$row['year']][$row['course']] = $row['count'];
}
$chart_data = json_encode(array_values($results));
This method uses the course names as the keys in the JSON, not course1, course2, etc. So you need to change
ykeys:['course','course','course','course','course'],
to:
ykeys:['BSIT','BSHRM','BSCS','BSTM','ABCOMM'],
The JSON in $chart_data already includes the square brackets around the array, so you don't need to add it around the echo. Use:
data: <?php echo $chart_data; ?>,
i have a select box in my HTML that contain some items,
anytime i select an item i need that item to query the database table row and display that database table field in a div tag element or a textarea element.
<select class="form-control" name="pd" required="required" id="pd">
<option selected="selected">--Select--</option>
<option value="Biology Chemistry Physics [BCP]">BCP</option>
<option value="Chemistry Mathematics Physics [CMP]">CMP</option>
<option value="Geography Mathematics Physics [GMP]">GMP</option>
</select>
At first, you will need a js event listener to trigger an ajax call, when the select box is changed:
// Attach event listeners when document is loaded (DOM tree is ready)
$(document).ready(function() {
// Trigger ajax call when select#pd is changed
// if you use jquery version lower than 1.7
// use $('#pd').live('change', function() {});
$('#pd').on('change', function() {
// The data to send though the ajax call
// if it's not the value of the select what you need
// to query your database, change it
var postData = {
'id': $(this).val(),
};
// test.php is the target of the ajax call
// if you have your php code in an other file,
// change it
$.post( 'test.php', postData, function(data, status) {
// $('#div_container') is where you want to display
// the result of your ajax call
$('#div_container').html(data);
});
});
});
In the test.php file you need to query the database, create the result you want to display in the div container mentioned above:
<?php
// Connect to the database, if needed
$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'database_name';
$mysqli = new mysqli($host, $user, $pass, $db);
// check connection
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// Data provided by the ajax call
$id = $mysqli->escape_string( $_POST['id'] );
// Query your data from database
// Obviously, you have to write a query to aquire the desired data
$query = "select * from table where column = '$id';";
// Create the required html structure from query data to return
// In this case, I want to create a table
// containing 4 columns(Col0..Col3) of my result set
ob_start();
if( $result = $mysqli->query($query) ) {
?><table>
<thead>
<tr>
<th>Col0</th>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody><?php
while( $row = $result->fetch_assoc() ) {
?><tr>
<td><?php echo $row['Col0']; ?></td>
<td><?php echo $row['Col1']; ?></td>
<td><?php echo $row['Col2']; ?></td>
<td><?php echo $row['Col3']; ?></td>
</tr><?php
}
?></tbody>
</table><?php
// Free result set
$result->free();
}
else {
// Handle failed query
printf("Error: %s\n", $mysqli->error);
exit();
}
// Close connection if needed
$mysqli->close();
// Gather the data from ob
$html = ob_get_contents();
ob_end_clean();
// Return the html structure
echo $html;
If you have any question about it, feel free to ask.
Hello people please help me with this! what i want to achieve is similar to twitter update notification bar that displays the number of new tweets and when you click on it; it drops the latest tweets on the previous tweets. i have been banging my head over this for days now, Here is what i tried.
//feed.php
<?php
session_start();
$cxn = mysqli_connect('localhost','root','','my_db');
$query = "SELECT insertion_time FROM feeds ORDER BY insertion_time DESC LIMIT 0,1";
$result = mysqli_query($cxn, $query) or die (mysqli_error($cxn));
$latest_feed = mysqli_fetch_assoc($result);
$_SESSION['latest_id'] = $latest_feed['insertion_time'];
$latest_news = $_SESSION['latest_id'];
echo $check = <<<JS_SCRIPT
<script>
interval = setInterval(function(){
check_update($latest_news);
},5000);
</script>
JS_SCRIPT;
?>
<script src='jquery.js'></script>
<script>
function check_update(old_feed)
{
$.post('server.php',{get_num_update: old_feed},function(data){
$("#update_bar").html(data);
}); //checks for number of updates
$.post('server.php',{retrieve_update: old_feed},function(data){
$("#hidden_div").html(data);
}); //retrieves the update into a div
}
$(function(){
$("#update_bar").click(function(){
$("#hidden_div").prependTo("#news_feed_container").fadeIn(500);
});
});
</script>
//server.php
if(isset($_POST['get_num_update']) && !empty($_POST['get_num_update']) && is_numeric($_POST['get_num_update']))
{
$old_feed = $_POST['get_num_update'];
$query = "SELECT id FROM feeds WHERE insertion_time > $old_feed ORDER BY insertion_time DESC";
$exec = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$num_updates = mysqli_num_rows($exec);
echo ($num_updates > 0) ? $num_updates.' new updates' : '';
}
if(isset($_POST['retrieve_update']) && !empty($_POST['retrieve_update']) && is_numeric($_POST['retrieve_update']))
{
while($result = mysqli_fetch_assoc($exec))
{
extract($result);
echo <<<HTML
//inserting the variable into html
HTML;
}
}
//
when the user clicks on the update_bar div which will be displaying something like '5 new updates' i want the update to pull down the latest feed from the hidden div, so everything doesn't really work as i would expect someone please help me out
Not tested, but it should approximately work...
//feed.php
<?php
session_start();
$cxn = mysqli_connect('localhost','root','','my_db');
$query = "SELECT insertion_time FROM feeds ORDER BY insertion_time DESC LIMIT 0,1";
$result = mysqli_query($cxn, $query) or die (mysqli_error($cxn));
$latest_feed = mysqli_fetch_assoc($result);
$_SESSION['latest_id'] = $latest_feed['insertion_time'];
$latest_news = $_SESSION['latest_id'];
echo $check = <<<JS_SCRIPT
<script>
// made the parameter of check_update a js variable and not hard coded in PHP
var latest_new=$latest_news;
// add a temp js variable for the last feed received (but not displayed)
var last_received=$latest_news;
interval = setInterval(function(){
check_update(latest_news);
},5000);
</script>
JS_SCRIPT;
?>
<script src='jquery.js'></script>
<script>
function check_update(old_feed)
{
// change your AJAX request to deal with JSON data and received several informations (number of new feed, insertion time of the last one)
$.post('server.php',{get_num_update: old_feed},function(data){
$("#update_bar").html(data.number_recents+" new updates.");
last_received=data.last_time;
},'json');
$.post('server.php',{retrieve_update: old_feed},function(data){
$("#hidden_div").html(data);
}); //retrieves the update into a div
}
$(function(){
$("#update_bar").click(function(){
$("#hidden_div").prependTo("#news_feed_container").fadeIn(500);
latest_new=last_received;
});
});
</script>
//server.php
if(isset($_POST['get_num_update']) && !empty(get_num_update']))
{
// header to serve JSON data
header('application/json');
$old_feed = $_POST['get_num_update'];
// request the number of new feed and the mst recent insertion time
$query = "SELECT count(*) as number,max(insertion_time) as last_time FROM feeds WHERE insertion_time > $old_feed ORDER BY insertion_time DESC";
$exec = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$feed_info = mysqli_fetch_assoc($exec);
//write the JSON data
echo '{"number_recents":'.$feed_info['number'].',"last_time":'.last_time.'}';
} else if(isset($_POST['retrieve_update']) && !empty($_POST['retrieve_update']) && is_numeric($_POST['retrieve_update']))
{
while($result = mysqli_fetch_assoc($exec))
{
extract($result);
echo <<<HTML
//inserting the variable into html
HTML;
}
}