Dynamic expandable datatable with multiple mysql tables? - php

I am working on dynamic j query data table where i want to show data from 3 tables.
It should be expandable.I am done to achieve with 1 table. but after joins another 2 tables its not working.
I am attaching my tables format and all pictures how should be my data look.
I have total 4 tables. employee_master,uk_slip,germany_slip,poland_slip.
each user have his pay_slips for each country for each month.
For eg. XYZ is employee.
he will get his 3 salary_slips for 2018-FEBRUARY.I want to show one datatable where first user will see his name then on expand datatable he will get in below format his all slips.
My current code is is showing only data from uk_slip. after UK another tables data should be display.
My model:
public function get_all_payslips()
{
$empid = $this->session->userdata('EMPLOYEE_ID');
$orgid = $this->session->userdata('CURRENT_ORG_ID');
$where = "EMPLOYEE_ID ='".$empid."' ";
$response = array();
$queryString = "SELECT
em.EMPLOYEE_ID,
em.EMPLOYEE_NAME
FROM
uk_slip assd,
employee_master em
WHERE
em.".$where."
GROUP BY em.EMPLOYEE_ID
order by em.EMPLOYEE_NAME asc";
$query = $this->db->query($queryString);
foreach ($query->result() as $data)
{
$result = array();
$result['EMPLOYEE_NAME'] = $data-> EMPLOYEE_NAME;
$queryString = "SELECT
mo.months,
MONTH((assd.pay_period)) as monthss,
YEAR((assd.pay_period)) as PAY_YEAR,
GROUP_CONCAT(DISTINCT(assd.id)) as action,
CONCAT(assd.ORG_ID,',',germany.ORG_ID,',',poland.ORG_ID) as org
FROM
uk_new_salary_slip assd,
employee_master em,
months mo,
germany_slip germany,
poland_slip poland
WHERE
assd.emp_id = ". $data->EMPLOYEE_ID ."
AND mo.id = MONTH((assd.pay_period))
GROUP BY monthss,PAY_YEAR
order by PAY_YEAR desc";
$query1 = $this->db->query($queryString);
$children = array();
foreach ($query1->result() as $data1)
{
$yearArray = array();
$yearArray['month'] = $data1->months;
$yearArray['year'] = $data1->PAY_YEAR;
$yearArray['org'] = $data1->org;
$yearArray['action'] = $data1->action;
array_push($children, $yearArray);
}
$result['children'] = $children;
array_push($response, $result);
}
return $response;
}
My View with jquery datatable:
$(document).ready(function()
{
var table = null;
$.ajax({
url:"<?php echo base_url('responsible/get_all_payslips'); ?>",
datatype:'json',
success: function(response)
{
var response1 = $.parseJSON(response);
console.log(JSON.stringify(response1['pay_slips']));
var data = response1['pay_slips'];
table = $('.datatables').DataTable({
columns : [
{
className : 'details-control',
defaultContent : '',
data : null,
orderable : false
},
{data : 'EMPLOYEE_NAME'},
],
data : data,
pagingType : 'full_numbers',
});
}
});
function format(data)
{
return '<div class="details-container">'+
'<table class="details-table table-bordered">'+
'<thead>'+
'<tr>'+
'<th>Year</th>'+
'<th>Month</th>'+
'<th>PDF</th>'+
'</tr>'+
'</thead>'+
'<tbody>'+
'<tr>'+
'<td>'+data.PAY_YEAR+'</td>'+
'<td>'+data.monthss+'</td>'+
'<td>'+'<a class="btn btn-success" href="data.action">'+data.action+'</a>'+'</td>'+
'</tr>'+
'<tr>'+
'<td>'+data.PAY_YEAR+'</td>'+
'<td>'+data.monthss+'</td>'+
'<td>'+'<a class="btn btn-success" href="data.action">'+data.action+'</a>'+'</td>'+
'</tr>'+
+'</tbody>'+
'</table>'+
'</div>';
};
$('.datatables tbody').on('click', 'td.details-control', function ()
{
var tr = $(this).closest('tr');
var row = table.row( tr );
console.log(row.data()['children']);
var childrenArray = row.data()['children'];
var check = '<div class="details-container">'+
'<table class="details-table table-bordered">'+
'<thead>'+
'<tr>'+
'<th>Year</th>'+
'<th>Month</th>'+
'<th>PDF</th>'+
'</tr>'+
'</thead>'+
'<tbody>';
for(var i=0;i<childrenArray.length;i++)
{
check +='<tr>'+
'<td>'+childrenArray[i].year+'</td>'+
'<td>'+childrenArray[i].month+'</td>';
var orgid = childrenArray[i].org.split(",");
var action = childrenArray[i].action.split(",");
var obj = {};
for (var k = 0; k < orgid.length; k++)
{
obj[orgid[k]] = action[k];
}
var arrayData = sortObject(action);
check +='<td>';
for(var j=0;j<arrayData.length;j++)
{
var country = "";
var color = "";
if(arrayData[j].key=="40")
{
country = "1";
color = "INDIANRED";
}
else if(arrayData[j].key=="41")
{
country = "2";
color = "LIGHTPINK";
}
else if(arrayData[j].key=="47")
{
country = "3";
color = "LIGHTSALMON";
}
else
{
country = "UK";
color = "DARKKHAKI";
}
check+='<a class="btn btn-success" style="background-color : ' + color + ';" href="<?php echo base_url()?>responsible/uk_pdf/'+arrayData[j].value+'">'+country+
'</a>|';
}
check +='</td></tr>';
}
check += '</tbody>'+
'</table>'+
'</div>';
if (row.child.isShown())
{
tr.next('tr').removeClass('details-row');
row.child.hide();
tr.removeClass('shown');
}
else
{
row.child(check).show();
tr.next('tr').addClass('details-row');
tr.addClass('shown');
}
});
});
function sortObject(obj)
{
var arr = [];
console.log(arr);
for (var prop in obj)
{
if (obj.hasOwnProperty(prop))
{
arr.push({
'key': prop,
'value': obj[prop]
});
}
}
arr.sort(function(a, b) { return a.value - b.value; });
return arr;
}
In all 3 slip_tables emp_id is common. then in each table having ORG_ID column. for UK having ORG_ID = 40, for GERMANY = 57, for POLAND = 47. In uk_slip having column pay_period for getting MONTH and YEAR with mysql functions MONTH and YEAR. and in germany and poland having pay_from to get the same.

Related

OpenCart 1.5.x.x ajax random value

I have dynamic block with show and hide products from table on random sort. But when the cash page is active, this part of page stom showing products and show only first product from query ... i do not understand how can i make it work with this effect and show 10 product on random soring ...
the query
$sql = "SELECT * FROM " . DB_PREFIX . "product";
$sql .= " WHERE sp_id = ".$id." AND show=1";
$sql .= " ORDER BY shop_id asc";
$query = $this->db->query($sql);
return $query->row;
and part with ajax :
<div id="content" class="group">
<div id="backItem">
<div id="footerItemContent">
</div>
<div id="footerItemDivider">-</div>
<div id="footerItemCustomer">...</div>
</div>
</div>
</div>
</div>
and my function
$(document).ready(function() {
var products = function() {
for ( var i = 0; i < complex.length; i++ ) {
var name = complex[i]['pr_name'];
var desc = complex[i]['pr_text'];
}
var i = 0;
var fnchange = function() {
$('#footerItemContent').animate({'opacity': 0}, 2000, function () {
$(this).text(desc);
}).animate({'opacity': 1}, 2500);
$('#footerItemCustomer').animate({'opacity': 0}, 2000, function () {
$(this).text(name);
}).animate({'opacity': 1}, 2500);
if( ++i < json.length ){
setTimeout(fnchange, 10000);
} else {
i = 0;
setTimeout(fnchange, 10000);
}
};
setTimeout(fnchange, 1);
};
setTimeout(feedbacks,1);
the name and desc should be an array
var names = new Array();
var desc = new Array();
for ( var i = 0; i < complex.length; i++ ) {
names[i] = complex[i]['pr_name'];
desc[i] = complex[i]['pr_text'];
}
and this
$(this).text(name[i]);
$(this).text(desc[i]);
I assume your json.length is the complex.length as the same thing

Chart from Database

I am trying to implement a chart from database, but I'm having a few problems...
I have a Database with 2 rows: Date, Pcr
My files .php:
Data.php
$query = "SELECT * FROM `table1` ORDER BY Date LIMIT 0 , 100";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
$dates=array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$dates[] = $row['Date'];
$dates[] = $row['Pcr'];
}
echo json_encode($dates);
I get the array:
["2015-06-14","0.77","2015-06-20","0.79","2015-09-24","0.88","2015-10-26","0.8","2015-10-30","0.7"]
I would like to get a dynamic chart from this array, but I don't know how to do that...
I have this static file:
chart.php
<div class="resultados"><canvas id="grafico"></canvas></div>
<script>
$(document).ready(function(){
$.ajax({
type:'POST',
url:'data.php',
success:function(data){
var valores = eval(data);
var date1 = valores[0];
var pcr1 = valores[1];
var date2 = valores[2];
var pcr2 = valores[3];
var date3 = valores[4];
var pcr3 = valores[5];
var date4 = valores[6];
var pcr4 = valores[7];
var Datos = {
labels : [date1,date2,date3,date4],
datasets : [
{
fillColor : 'rgba(255,0,0,0.1)',
strokeColor :'rgba(255,0,0,100)',
pointColor : 'rgba(255,0,0,100)',
pointStrokeColor:"#e32636",
pointHighlightFill:"#bbf",
pointHighlightStroke:"rgba(255,0,0,255)",
data : [pcr1,pcr2,pcr3,pcr4]
}
]
}
var contexto = document.getElementById('grafico').getContext('2d');
window.Barra = new Chart(contexto).Line(Datos, { responsive : true });
}
});
return false;
}
)
</script>
Could someone help me to find what I have to put in Data:[]?
Thank you very much
php:
$dates=array();
$pcrs=array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$dates[] = $row['Date'];
$pcrs[] = $row['Pcr'];
}
$data = ["dates"=>$dates,"pcrs"=>$pcrs];
echo json_encode($data);
js:
$(document).ready(function(){
$.ajax({
type:'GET',
url:'data.php',
success:function(data){
var Datos = {
labels : data.dates,
datasets : [
{
fillColor : 'rgba(255,0,0,0.1)',
strokeColor :'rgba(255,0,0,100)',
pointColor : 'rgba(255,0,0,100)',
pointStrokeColor:"#e32636",
pointHighlightFill:"#bbf",
pointHighlightStroke:"rgba(255,0,0,255)",
data : data.pcrs
}
]
}
var contexto = document.getElementById('grafico').getContext('2d');
var chrt = new Chart(contexto).Line(Datos, { responsive : true });
}
});
return false;
}
)

How to access JSON values returned by AJAX call

I have written AJAX code to fetch MySQL data and show it on an HTML page. But my output is not showing on the page.
What am I doing wrong?
PHP:
function nav() {
$this->dbConnect();
$qry="SELECT pid, ptitle FROM pages WHERE pagepub='1' ORDER BY porder ASC";
$result=mysqli_query($this->connect,"$qry") or die('MySql Error! ' . mysqli_error());
$results = array();
while($row=mysqli_fetch_row($result)) {
$results[] = $row;
}
echo json_encode($results);
$this->dbclose();
}
Here is the output of my PHP file:
[
{
"pid":"1",
"ptitle":"One Time Registration Tips"
},
{
"pid":"2",
"ptitle":"First men in India"
},
{
"pid":"3",
"ptitle":"First Women in India"
}
]
JavaScript / HTML:
<div id="output">this element will be accessed by jquery and this text will be replaced</div>
<script type="text/javascript" src="dist/js/jquery.js"></script>
<script type="text/javascript">
$(function () {
jQuery.ajax({
url: 'http://keralapsctuts.com/app/category.php',
data: "",
dataType: 'json',
success:function(data) {
var id = data[0]; //get id
var title = data[1]; //get name
$('#output').html(" <a class='list-group-item' href='"+id+"'"+title+" <i class='fa fa-chevron-right pull-right'></i></a>");
}
});
});
</script>
As you returning more rows, you should use for if you want to iterate through them.
success:function(data) {
var result = "";
for(var i=0; i < data.length; i++) {
var id = data[i]["pid"]; //get id
var title = data[i]["ptitle"]; //get name
result += "<a class='list-group-item' href='"+id+"'>"+title+"<i class='fa fa-chevron-right pull-right'></i></a>";
}
$('#output').html(result); //Set output element html
}
Given your output of:
[{"pid":"1","ptitle":"One Time Registration Tips"},{"pid":"2","ptitle":"First men in India"},{"pid":"3","ptitle":"First Women in India"}]
Your data would be addressable like so:
success:function(data){
var id = 0;
var title = "";
$.each(data, function(k, v){
id = v.pid;
title = v.ptitle;
$('#output').append("<a class='list-group-item' href='"+id+"'>"+title+"<i class='fa fa-chevron-right pull-right'></i></a>");
});
}

Jquery datatables functions not working

I would like to ask a question and I need a little help from you guys.
I would like to use jquery Datatable plugin in my project but something going wrong.
The table is displayed properly, but none of the datatable functions working.
Here is my code:
function get_answer(get_date, get_id) {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var date = get_date;
var id = get_id;
var data = {
'action': 'get_answers_ajax',
'date': date,
'id': id
};
var table_structure = '<table id="result-' + id + '" class="table table-striped table-hover table-dynamic display"><thead class="result_head"><tr><th></th></tr></thead><tbody class="result_body"><tr><td></td></tr></tbody></table>';
jQuery('#tabs-' + id).append(table_structure);
jQuery.post(ajaxurl, data, function (response) {
if (response) {
var obj = JSON.parse(response);
var heads = [];
var results = [];
jQuery.each(obj, function (key, res) {
if (jQuery.inArray(res.label, heads) == '-1')
{
heads.push(res.label);
}
results.push(res.value);
});
var head = jQuery('#tabs-' + id + ' .result_head tr');
head.empty();
jQuery.each(heads, function (key, value) {
head.append('<th>' + value + '</th>');
});
var body = jQuery('#tabs-' + id + ' .result_body');
body.empty();
if (results.length > 0) {
body.append('<tr role="row" class="odd">'); // Open tr
var count_heads = heads.length;
var count_answ = 0;
jQuery.each(results, function (key, value) {
if (value.substring(0, 4) == 'http') {
body.find('tr').last().append('<td><img src="' + value + '" alt="none" width="200px" height="200px" /></td>');
} else {
body.find('tr').last().append('<td>' + value + '</td>');
}
count_answ++;
if ((count_answ % count_heads) == 0) {
body.find('tr').last().find('td').last().after('</tr>');
body.find('tr').last().after('<tr role="row" class="even">');
}
});
body.find('tr').last().after('</tr>'); // Close tr
}
}
});
jQuery('#result-' + id).dataTable(
{
"ordering": true,
"searching": true
}
);
The heads and the reults array looks like this:
Heads => ["Eredmény", "Felhasználó", "Dátum"]
Results => ["666", "Wathfea", "2014-10-14 12:55:12", "hdjjdbkudbh", "Zsolti", "2014-10-14 16:44:55", "kfhkfvjhdgh", "Zsolti", "2014-10-14 17:16:29"]
My PHP function which one gives back the data is this:
function get_answers() {
global $wpdb;
$date = $_POST['date'];
$form_id = $_POST['id'];
$date_pice = explode(' - ', $date);
$question = array();
$answer = array();
$sql_answers = "SELECT lead.date_created, detail.field_number, detail.value, detail.form_id, meta.display_meta FROM wp_rg_lead_detail AS detail INNER JOIN wp_rg_lead AS lead ON detail.lead_id = lead.id INNER JOIN wp_rg_form_meta AS meta ON detail.form_id = meta.form_id WHERE lead.date_created BETWEEN '{$date_pice[0]}' AND '{$date_pice[1]}' AND detail.form_id = '{$form_id}' ";
$answers = $wpdb->get_results($sql_answers);
foreach ($answers as $ans_info) {
$meta = self::bsp_unserialize($ans_info->display_meta);
foreach ($meta[fields] as $fields) {
if ($fields["id"] == $ans_info->field_number) {
$question["kerdes"] = $fields["label"];
$answer["valasz"] = $ans_info->value;
}
}
$toJSON[] = array("label" => $question["kerdes"], "value" => $answer["valasz"]);
}
echo json_encode($toJSON);
die();
}
So, the table shows all of the data in it, but If i would like to search or ordering or paginating nothings works.
Any hint about it?
Thx a lot
I could solve the problem.
I just modifed the append method, and now I making a html string with the ready html element and I jut append that at the end of the process.
jQuery(document).ready(function () {
var table_structure = '<table id="result" class="table table-striped table-hover table-dynamic display"><thead class="result_head"><tr><th></th></tr></thead><tbody class="result_body"><tr><td></td></tr></tbody></table>';
jQuery('#table').append(table_structure);
var heads = ["Result", "User", "Date"];
var results = ["666", "Wathfea", "2014-10-14 12:55:12", "hdjjdbkudbh", "Zsolti", "2014-10-14 16:44:55", "kfhkfvjhdgh", "Zsolti", "2014-10-14 17:16:29"];
jQuery('.result_head tr').empty();
jQuery.each(heads, function (key, value) {
jQuery('.result_head tr').append('<th>' + value + '</th>');
});
var body = jQuery('.result_body');
body.empty();
if (results.length > 0) {
var count_heads = heads.length;
var count_answ = 0;
var html = "";
jQuery.each(results, function (key, value) {
if ((count_answ % count_heads) === 0) {
html += '<tr>';
}
if (value.substring(0, 4) == 'http') {
html += '<td><img src="' + value + '" alt="none" width="200px" height="200px"/></td>';
} else {
html += '<td>' + value + '</td>';
}
count_answ++;
if ((count_answ % count_heads) === 0) {
html += '</tr>';
body.append(html);
html = '';
}
});
}
jQuery('#result').dataTable(
{
"ordering": true,
"searching": true
}
);
});

array from php to js with ajax

i have this code on the server side:
<?php
header('Content-Type: text/html; charset=utf-8');
require "../general.variables.php";
require "../functions_validation.php";
require "../functions_general.php";
require "../../db_con.php";
$keyword = mysql_real_escape_string($_POST["keyword"]);
$query = mysql_query("
SELECT user_id, user_fullname, user_area, user_city, user_quarter, user_tmb
FROM `migo_users`
WHERE (
user_fullname LIKE '%".$keyword."%' AND user_id NOT IN (".$superAdmins2string.")
)
ORDER BY tmb_set DESC, user_fname ASC
LIMIT 7;
");
$i = 0;
while ($userInfo = mysql_fetch_array($query)) {
$area_name = mysql_fetch_array(mysql_query("
SELECT area_name
FROM `migo_areas`
WHERE
area_id='".$userInfo['user_area']."';
"));
$city_name = mysql_fetch_array(mysql_query("
SELECT city_name
FROM `migo_cities`
WHERE
city_id='".$userInfo['user_city']."';
"));
if ($userInfo['user_quarter'] != 0) {
$quarter_name = mysql_fetch_array(mysql_query("
SELECT quarter_name
FROM `migo_quarters`
WHERE
quarter_id='".$userInfo['user_quarter']."';
"));
}
else {
$quarter_name['quarter_name'] = "";
}
$rsl[$i]['user_id'] = $userInfo['user_id'];
$rsl[$i]['user_fullname'] = $userInfo['user_fullname'];
$rsl[$i]['user_area_name'] = $area_name['area_name'];
$rsl[$i]['user_city_name'] = $city_name['city_name'];
$rsl[$i]['user_quarter_name'] = $quarter_name['quarter_name'];
$rsl[$i]['user_tmb'] = $userInfo['user_tmb'];
$i++;
}
echo json_encode($rsl);
mysql_close();
?>
and this code on the client side:
$.ajax({
type : 'POST',
url : 'php/general.ajax/header_search.php',
//async : false,
//cache : false,
dataType : 'json',
data: {
keyword : sb_keyword
},
success : function(data) {
var hs_hits = 0;
var hs_row_nr = 1;
var hs_results = "<div class='sb_spacing'></div><div id='sb_rows_cont'>";
if (data != null) {
$.each(data, function(index, arr) {
hs_hits++;
if (arr['user_quarter_name'] != "") {
var quarter_text = " - " + arr['user_quarter_name'];
}
else {
var quarter_text = "";
}
hs_results = hs_results + "<a class='search_links' href=profile.php?id=" + arr['user_id'] + "><div class='sbr_row' row_nr='" + hs_row_nr + "'><div class='sbr_imgFrame'><img src='images/user_48x48/" + arr['user_tmb'] + "' alt=''></div><div class='sbr_name'>" + arr['user_fullname'].replace(regexp_hs_user_fullname, '<span>$&</span>') + "</div><div class='sbr_area'>" + arr['user_area_name'] + "</div><div class='sbr_area'>" + arr['user_city_name'] + quarter_text + "</div></div></a>";
hs_row_nr++;
});
}
if (hs_hits > 0) {
hs_results = hs_results + "</div><div class='sb_spacing'></div><a class='search_links' href='search.php?name=" + sb_keyword + "'><div id='sbr_botttom'>Se flere resultater for <span class='gay'>" + sb_keyword + "</span></div></a>";
$("#sb_results").html(hs_results).show();
searchSet = 1;
total_rows = hs_hits;
$("#sb_rows_cont > a:first .sbr_row").addClass('sbr_row_act');
on_a = $("#sb_rows_cont > a:first");
first_a = on_a;
last_a = $("#sb_rows_cont > a:last");
sb_url = $(on_a).attr('href');
search_navigator_init();
}
else {
$("#sb_results").hide();
searchSet = 0;
}
},
error : function() {
alert("ajax error");
}
});
one problem tho, if the query gives 0 results, and the each function tries to run on the client side my js code stops working..
so i was wondering what i could do here.
how can i retrieve the amount of hits from the server side, before i run the each loop?
You're instantiating $rsl in the middle of a loop (implicitly), but you aren't entering the loop unless you have at least one entry.
Instantiate $rsl up above your while loop:
...
$i = 0;
$rsl = array();
while ($userInfo = mysql_fetch_array($query)) {
...
And now when you encode it, it is an empty array instead of null. This will also save your HTTP error_log, and generally be happier. : )
I would try json_encode() your PHP array to allow JavaScript to eval it as a native JS object.
echo json_encode($some_array);
Just a note, json_encode() is only available for PHP versions 5.2 and higher.
$.getJSON('ajax.php',{form data}, functon(data){
if(data == '') return;
});

Categories