For a few days I am busy solving following. I would like to load bootstrap table through a click into a <div>. My situation:
index.php
<div id="page-content">
<div id="data" class="animated"></div> on page load, loaddata
<div id="table" class="animated">
<table id="report-table" data-toggle="table"></table>
</div> hidden, onclick hide #data and show #table
</div>
loaddata.php
$tab_id = $_POST['tab_id'];
$tab_name = $_POST['tab_name'];
$selectTabbladen = $gebruiker_data->runQuery("SELECT * FROM documenten LEFT JOIN relaties ON documenten.relatie_id = relaties.relatie_id LEFT JOIN clienten ON documenten.clienten_id = clienten.clienten_id WHERE documenten.tab_id = $tab_id ORDER BY document_datum");
if (!$selectTabbladen->execute()) return false;
if ($selectTabbladen->rowCount() > 0) {
$tabblad_data = array();
while ($tabdata = $selectTabbladen->fetch()) {
$tabblad_data[] = array(
"id" => $tabdata['id'],
"document_soort" => $tabdata['document_soort'],
"voornaam" => $tabdata['voornaam'],
"relatie_naam" => $tabdata['relatie_naam'],
"tabblad" => $tabdata['document_status'],
"status" => $tabdata['document_status'],
"aanmaak_datum" => $tabdata['document_datum'] = date('d M Y H:i:s'),
"laatst_gewijzigd" => $tabdata['document_datumgewijzigd'] = date('d M Y H:i:s'),
);
}
print '</tbody>
</table>
';
$json_data = json_encode($tabblad_data);
print_r ($json_data);
}
ajax
$('body').on('click', '.tab_data', function () {
content.hide();
$('#dataa').show();
var tab_id = $(this).attr("id");
$.ajax({
type: "POST",
url: "loaddata.php",
data: {
tab_id: tab_id
},
dataType:"json",
success : function(data) {
$('#report-table').bootstrapTable({
data: data
});
}
});
});
As result I'm getting:
No matching records found
Can you help me please. What am I doing wrong?
If you have passed your tab_id correctly then the problem is with your query
Instead of
$selectTabbladen = $gebruiker_data->runQuery("SELECT * FROM documenten LEFT JOIN relaties ON documenten.relatie_id = relaties.relatie_id LEFT JOIN clienten ON documenten.clienten_id = clienten.clienten_id WHERE documenten.tab_id = $tab_id ORDER BY document_datum");
try this
$selectTabbladen = $gebruiker_data->runQuery("SELECT * FROM documenten LEFT JOIN relaties ON documenten.relatie_id = relaties.relatie_id LEFT JOIN clienten ON documenten.clienten_id = clienten.clienten_id WHERE documenten.tab_id = ".$tab_id." ORDER BY document_datum");
Updated
Try this
$('#report-table').bootstrapTable({
'load': data
});
Related
i have problem with the post value in my form
i show you my code and see if you can help me
<script src="//netsh.pp.ua/upwork-demo/1/js/typeahead.js"></script>
<script>
$(document).ready(function() {
$('#ville').on('change', function(){
var id_ville = this.value;
$.ajax({
type: "post",
url: "lycee.php",
data: 'id_ville=' + id_ville,
success: function(result){
$("#lycee").html(result);
}
});
$('input.lycee').typeahead({
name: 'lycee',
remote: 'lycee.php?query=%QUERY'
});
});
})
</script>
<script >
and this is my php part code
$id_ville = mysql_real_escape_string($_POST['id_ville']);
if($id_ville!='') {
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = $conn->query ("SELECT nom_lycee
FROM ville_lycee
INNER JOIN ville ON ville.id_ville = ville_lycee.id_ville
INNER JOIN lycee ON lycee.id_lycee = ville_lycee.id_lycee
WHERE ville.id_ville = '" . $id_ville . "'
AND lycee.nom_lycee LIKE '%{$query}%' ");
$options = "<label value=''></label>";
$array = array();
while ($row = $sql->fetch_assoc()) {
$array[] = array (
'label' => $row['nom_lycee'],
'value' => $row['nom_lycee'],
);
}
echo json_encode ($array);
}
}
the problem is that i need the id_ville value first and then the Query to filtre
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.
I am trying to select data based on a value, I have a form which selects data from a table of teams, I need to to get the ID of that row from the select dropdown (which I can do) but then use that to determine the data that it needs to select when im doing an AJAX request. Here goes:
Teams page - This page draws my graph which pulls in data via AJAX to draw the graph and its values:
<form action="teams.php?dashboard_id=<?php echo $dashboard_id; ?>" method="POST">
<select name="teamId">
<option selected="true" disabled="disabled">Please choose...</option>
<?php
$sql = "SELECT * FROM teams WHERE dashboard_id = $dashboard_id";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value=' . $row["team_id"] . '>' . $row["team_name"] . '</option>';
}
}
?>
</select>
<button class="compare">View</button>
</form>
<?php
if (!empty($_POST["teamId"])) {
$teamSelect = $_POST["teamId"];
echo $teamSelect;
}else{
echo "";
}
?>
<div style="max-width: 450px;">
<canvas id="mycanvas" class="container"></canvas>
</div>
Here is the PHP page that im doing the SELECT on:
<?php
include 'config.php';
$teamID = $_POST['teamId'];
$query = sprintf("SELECT
tm.member_id,
tm.team_id,
m.member_id,
m.firstName,
m.lastName,
m.score_1,
m.score_2,
m.score_3,
m.score_4,
m.score_5,
m.score_6,
m.score_7,
m.score_8,
m.dashboard_id,
t.team_id,
t.team_name,
t.dashboard_id
FROM team_members tm
JOIN members AS m
on m.member_id = tm.member_id
JOIN teams AS t
on t.team_id = tm.team_id
WHERE tm.team_id = '$teamID'"); // This need to be dynamic and got from the POST request on the form above.
$result = $conn->query($query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$result->close();
$conn->close();
header('Content-type: application/json');
print json_encode($data);
?>
Im drawing the graph out via another file:
$(document).ready(function(){
$.ajax({
url : "http://localhost/acredashAdv/teamData.php",
type : "GET",
success :function(data){
console.log(data);
var chartata = {
labels: [
"Strategic Development and Ownership",
"Driving change through others",
"Exec Disposition",
"Commercial Acumen",
"Develops High Performance Teams",
"Innovation and risk taking",
"Global Leadership",
"Industry Leader"
]};
var ctx = $("#mycanvas");
var config = {
type: 'radar',
data: chartata,
animationEasing: 'linear',
options: {
legend: {
display: true,
position: 'bottom'
},
tooltips: {
enabled: true
},
scale: {
ticks: {
fontSize: 15,
beginAtZero: true,
stepSize: 1
}
}
},
},
LineGraph = new Chart(ctx, config);
var colorArray = [
["#7149a5", false],
["#58b7e0", false],
["#36bfbf", false],
["#69bd45", false],
["#5481B1", false],
["#6168AC", false]
];
for (var i in data) {
tmpscore=[];
tmpscore.push(data[i].score_1);
tmpscore.push(data[i].score_2);
tmpscore.push(data[i].score_3);
tmpscore.push(data[i].score_4);
tmpscore.push(data[i].score_5);
tmpscore.push(data[i].score_6);
tmpscore.push(data[i].score_7);
tmpscore.push(data[i].score_8);
var color, done = false;
while (!done) {
var test = colorArray[parseInt(Math.random() * 6)];
if (!test[1]) {
color = test[0];
colorArray[colorArray.indexOf(test)][1] = true;
done = !done;
}
}
newDataset = {
label: data[i].firstName+' '+data[i].lastName,
borderColor: color,
backgroundColor: "rgba(0,0,0,0)",
data: tmpscore,
};
config.data.datasets.push(newDataset);
}
LineGraph.update();
},
});
});
This is all great but in my select query I need the WHERE clause to show me data determined on the value of the team ID and not a static value but im not sure how to pass across the ID from the select back to the AJAX file?
Use sessions then. $_SESSION['teamID'] = $teamID. Then you can reference it anywhere. Be sure to start the session at the top of each php file using sessions.
session_start();
$teamID = $_POST['teamId'];
$_SESSION['teamID'] = $teamID;
References:
http://php.net/manual/en/function.session-start.php
http://php.net/manual/en/book.session.php
I tried to modified the long polling code to fit my situation.
I would like to count the total number from mysql and if the number changes (increase or decrease), it will notify me.
The problem is the while loop keep looping. How can I stop it? I just need to have notification whenever the total sum change.
<?php
include("db.php");
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$old_totalsum = $row['totalsum'];
}
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
var old_totalsum =<?php echo $old_totalsum; ?>;
function waitForMsg(){
$.ajax({
type: "GET",
url: "poll.php?old_totalsum=" + old_totalsum,
async: true,
cache: false,
success: function(data){
var json = "eval(+(" + data + ")+)";
if(json['msg'] != "") {
alert(data);
}
old_msg_id = json['old_msg_id'];
setTimeout('waitForMsg()',1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()',15000);
}
}); // end ajax
} //end waitformsg
$(document).ready(function(){
waitForMsg();
});
</script>
</head>
<body>
<div id="chat">
</div>
</body>
</html>
<----------------------------------------------------------->
poll.php
<----------------------------------------------------------->
<?php
include("db.php");
$old_totalsum = $_GET['old_totalsum'];
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$last_sum = $row['totalsum'];
}
while($last_sum < $old_totalsum || $last_sum > $old_totalsum)
while($last_sum <= $old_totalsum)
{
usleep(1000);
clearstatcache();
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$last_sum = $row['totalsum'];
//echo $last_sum;
//return;
}
}
$response = array();
$response['msg'] = 'new';
$response['old_msg_id'] = $last_sum;
echo json_encode($response);
?>
<------------------------------------------->
I expected logic like this:
$latest_sum= -1;
// Loop until sum from DB is different from what was passed in
while( $latest_sum == -1 || $latest_sum!= $old_sum ){
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$lastest_sum = $row['totalsum'];
}
}
$response = array();
$response['msg'] = 'new';
$response['old_msg_id'] = $latest_sum;
echo json_encode($response);
If it takes a long time to change, then Apache (or whatever is running PHP) will likely cancel the request. This is also going to run lots of queries on the db which is expensive.
So it would be better to have your loop in the javascript. It would call a function that would just return the latest sum from the database. The javascript should wait a second or more inbetween each request.
If performance is still too hard on the database, then the php should somehow cache the value every minute and return the cached value.
I've built up a script that is to get users posts from a database, and I'm almost there. The ajax calls and I get the 10 posts in the response in Firebug, only it shows only 1 post in the page when I click load more. What do I need to add to the code below to show 9 more results?
AJAX
<script type="text/javascript">
$(document).ready(function(){
$('.load_more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#load"+ID).html('Loading...');
$.ajax({
type: "POST",
url: "include/load_more_home_posts.php",
cache: false,
dataType: "json",
data: { streamitem_id: ID},
cache: false,
success: function(stream){
$("#articles").prepend("<div id='divider-"+stream['streamitem_id']+"'><div class='userinfo'>X</div><a href='/profile.php?username="+stream['username']+"'>"+stream['first']+" "+ stream['middle']+" "+stream['last']+"<span class='subtleLink'> said</span><br/><a class='subtleLink' style='font-weight:normal;'>"+stream['streamitem_timestamp']+"</a><hr>"+stream['streamitem_content']+"<div style='height:20px;' class='post_contextoptions'><div id='streamcomment'><a style='cursor:pointer;' id='commenttoggle_"+stream['streamitem_id']+"' onclick=\"toggle_comments('comment_holder_"+stream['streamitem_id']+"');clearTimeout(streamloop);swapcommentlabel(this.id);\">Write a comment...</a></div><div id='streamlike'><a title='Like "+stream['first']+" "+ stream['middle']+" "+stream['last']+"s status' id='likecontext_"+stream['streamitem_id']+"' style='cursor:pointer;' onClick=\"likestatus("+stream['streamitem_id']+",this.id);\"><div style='width:50px;' id='likesprint"+stream['streamitem_id']+"'>Like</a></div><div style='width:50px;' id='likesprint"+stream['streamitem_id']+"'><a title='See who likes "+stream['first']+" "+ stream['middle']+" "+stream['last']+"s status' href='include/likes.php?streamitem_id="+stream['streamitem_id']+"' /></a></div></div></form></div><div id='streamdislike'><a id='dislikecontext_"+stream['streamitem_id']+"' style='cursor:pointer;' onClick=\"dislikestatus("+stream['streamitem_id']+",this.id);\"><div style='width:70px;' id='dislikesprint"+stream['streamitem_id']+"'>Dislike</a></div><div style='width:70px;' id='dislikesprint"+stream['streamitem_id']+"'></div></div></form><div class='stream_comment_holder' style='display:none;' id='comment_holder_"+stream['streamitem_id']+"'><div id='comment_list_"+stream['streamitem_id']+"'></div><div class='stream_comment_inputarea'><form id='mycommentform' method='POST' class='form_statusinput'>\
<input type='hidden' name='streamidcontent' id='streamidcontent' value='"+stream['streamitem_id']+"'>\
<input type='input' name='commentingcontents' id='commentingcontents' placeholder='Say something' autocomplete='off'>\
<input type='submit' id='button' value='Feed'><br/></div></div>");
// remove the previous load more link
$("#load"+ID).remove();
}
});
}
return false;
});
});
</script>
include/load_more_home_posts.php
<?php
session_start();
include("rawfeeds_load.php");
if (isset($_POST['streamitem_id']) && $_POST['streamitem_id'] != "") {
$lastID = mysqli_real_escape_string($mysqli,$_POST['streamitem_id']);
$json= array();
$following_string = mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="SELECT d.*, c.*, u.*
FROM streamdata AS d
JOIN streamdata_comments AS c ON d.streamitem_id = c.comment_streamitem
JOIN users AS u ON u.id = c.comment_poster
WHERE c.comment_poster = '$following_string'
AND d.streamitem_id < '$lastID'
AND (d.streamitem_target = '$following_string' OR
d.streamitem_creator = '$following_string')
ORDER BY d.streamitem_id DESC LIMIT 10";
$chant = mysqli_query($mysqli, $call) or die(mysqli_error($mysqli));
$json['streams'] = array();
while ($resultArr = mysqli_fetch_assoc($chant)) {
$json['streamitem_id'] = $resultArr['streamitem_id'];
$json['streamitem_content'] = $resultArr['streamitem_content'];
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_content'] = $resultArr['comment_content'];
$json['comment_poster'] = $resultArr['comment_poster'];
$json['comment_datetime'] = Agotime($resultArr['comment_datetime']);
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
$json['streamdata'][] = $json;
}
echo json_encode($json);
}
?>
You recive from PHP an JSON like [{item1, item2},{item11, item12},...] and without iterate over it you are using only first group. I think the best and the easiest way will be using $.getJSON function instead of $.ajax. Look here at the second example, I think it is all you need to handle JSON received from PHP.