ajax tooltip doesn't load the data - javascript

I am making a web site in mvc structure. This site shows a table and on that table there is a tooltip which shows more detail of the cell. However, the data in tooltip is not loaded. (except tooltip everything works fine)
This tooltip data is loaded from mySQL and it has two input variables deptName and deptPart.
Tooltip worked well when I typed in random things instead of loading data...I can't find a reason why it gets an error :(
My Model for tooltip is
function getTooltipML($deptName, $deptPart)
{
$sql = "Call TooltipML('$deptName', '$deptPart')";
$tooltipML = $this->sqlExecution($sql);
return json_encode($tooltipML);
}
function getTooltipWillLeave($deptName, $deptPart)
{
$sql = "Call TooltipWillLeave('$deptName', '$deptPart')";
$tooltipWL = $this->sqlExecution($sql);
return json_encode($tooltipWL);
}
My Controller for tooltip is
function view()
{
$deptName = $_POST['deptName'];
$deptPart = $_POST['deptPart'];
$tooltipML = $this ->model -> getTooltipML($deptName, $deptPart);
$tooltipWL = $this ->model -> getTooltipWillLeave($deptName, $deptPart);
//call view to push the data into the view
$this->requireView('ManagementMasterView', [
'page' => "DashboardDetail",
'tooltipML' =>$tooltipML,
'tooltipWL' => $tooltipWL
]);
}
function tooltip(){
$deptName = $_POST['deptName'];
$deptPart = $_POST['deptPart'];
echo json_encode ($this -> model -> getTooltipML($deptName, $deptPart));
echo json_encode ($this -> model -> getTooltipWillLeave($deptName, $deptPart));
}
My view for the tooltip is
<div class="dash_table_container">
<?php
// pre-process data
$printedData = json_decode($data['resourceStatus'], true);
$tableHeader = ['deptName', 'deptPart', 'C', 'D', 'E', 'F'];
$tooltipData1 = json_decode($data['tooltipMLEx'], true);
$tooltipData2 = json_decode($data['tooltipWL'], true);
// //Build up a table
table1('dash-tb1', $tableHeader, $printedData, $tooltipData1, $tooltipData2);
?>
</div>
//function below is in separate php file but I just added in view here for better readability
function table1($tableId, $header, $data, $tooltip1, $tooltip2){
// header build
echo '
<table class="display table table-striped" id="'.$tableId.'">
<thead>
<tr class="table-primary">
<th>#</th>';
foreach ($header as $columnVal){
echo '<th>'.$columnVal.'</th>';
}
echo '
</tr>
</thead>
<tbody>';
$index = 0;
$tooltip1 = "";
$tooltip2 = "";
foreach ($data as $row){
$tooltip1;
$tooltip2;
$index++;
echo '
<tr id="'.$row['deptName'].'" data-id="'.$row['deptPart'].'">
<td>'.$index.'</td>
<td>'.$row['deptName'].'</td><td>'.$row['deptPart'].'</td><td>'.$row['C'].'</td>
<td class = "CellWithComment"><span class="CellComment">'.$tooltip1.'</span>'.$row['D'].'</td>
<td class = "CellWithComment"><span class="CellComment">'.$tooltip2.'</span>'.$row['E].'</td>
<td>'.$row['F'].'</td>';
}
echo '
</tr>
</tbody>
</table>';
}
and my javascript is
$(document).ready(function(){
// Add tooltip
$('.CellComment').tooltip({
delay: 500,
placement: "bottom",
title: tooltipDetails,
html: true
});
});
// Get employee details for tooltip
function tooltipDetails(deptName, deptPart){
var deptName = this.deptName;
var deptPart = $(this).attr('data-id');
var tooltipText = "";
$.ajax({
url: '/hrmsystem/Dashboard/tooltip',
method: "POST",
data: {dept_Name:deptName, dept_Part:deptPart},
dataType: "JSON",
async: false,
success: function(response){
tooltipText = response;
}
});
return tooltipText;
}
Thank you very much for your tips.

Related

How can I pass id of multiple row selection to print page at the time of inserting data

I am inserting data successfully by selecting multiple row table data but at the same time I want to print data on print page.
In above image I select only 3 record and insert in data base at the time of insert that selected data I want show on my print page.
Create page:
<form>
<table id="pending_collection_table"> </table>
<input type="button" id="allocate" value="allocate" name="allocate">
</form>
<script>
$('#allocate').click(function (event) {
event.preventDefault();
var allVals = [];
$('input[name=selectedBilties]:checked').each(function() {
allVals.push($(this).val());
});
var formData = new FormData();
var agent = $('#agent').val();
var rec_type = $('#rec_type').val();
formData.append("agent",agent);
formData.append("rec_type",rec_type);
for (var i = 0; i < allVals.length; i++) {
formData.append('due_ids[]', allVals[i]);
}
alertify.confirm('Payment Recovery Allocation', 'Do you want to Allocate ?', function(){
$.ajax({
url :"<?php echo base_url();?>crossing/payment_rec_allocation/PaymentRecAllocationController/createPaymentAllocation",
type:"POST",
dataType: "json",
data:formData,
contentType:false,
cache:false,
processData:false,
success: function(data){
if(data.PaymentRecAllocation.form_status=='false'){
}
else if(data.PaymentRecAllocation.form_status=='true'){
alertify.confirm('Payment Recovery Allocation', 'Do you want to print ? ', function(){
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage";
setTimeout(location.reload.bind(location), 2000);
},
function(){
location.href="<?php echo base_url(); ?>", 'refresh';
});
}
}
});
}, function(){
});
});
</script>
Contoller:
public function createPaymentAllocation()
{
$bilty_ids = $this->input->post('due_ids');
$biltyCount = count($bilty_ids);
$agent = $this->input->post('agent');
$due_to = $this->input->post('due_to');
for($i = 0; $i < $biltyCount; $i++) {
$data = array(
'agent_id' =>$agent,
'pay_dueto' =>$due_to,
'mr_no' =>$bilty_ids[$i],
);
$modelResult = $this->PayRecAllModel->inserPaymentAllocation($data);
}
if($modelResult){
$data['PaymentRecAllocation'] = array(
'form_status' => 'true',
'form_message' => 'Payment Recovery has been successfully Allocate'
);
}else{
$data['PaymentRecAllocation'] = array(
'form_status' => 'false',
'form_message' => 'Something went wrong.'
);
}
echo json_encode($data);
}
Model:
public function inserPaymentAllocation($data){
if($this->db->insert('payment_rec_allocn', $data)){
return true;
}else {
return false;
}
}
And now my print function on controller
public function printCollectionRecPage(){
$this->load->view('template/header');
$data= array();
$data['collnR'] = $this->PayRecAllModel->printCollectionRecPage();
$this->load->view('crossing/payment_rec_allocation/printCollectionRecovery',$data);
$this->load->view('template/footer');
}
model of print page:
public function printCollectionRecPage(){
$this->db->select('*');
$this->db->from('payment_rec_allocn');
$this->db->join('crossing_cash_memo', 'payment_rec_allocn.mr_no = crossing_cash_memo.mr_no');
$this->db->where('total !=','0');
$query = $this->db->get();
return $query->result();
}
How I can pass ids in print page.
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage";
How can I pass that selected ids on print page.
And my print page I have table to show data of selected data on inset time.
You can use insert_id() function
public function inserPaymentAllocation($data){
if($this->db->insert('payment_rec_allocn', $data)){
$insert_id = $this->db->insert_id();
return $insert_id;
}else {
return false;
}
}
store returned ids into array
$modelResult[] = $this->PayRecAllModel->inserPaymentAllocation($data);
if(!empty($modelResult)){
$data['PaymentRecAllocation'] = array(
'form_status' => 'true',
'form_message' => 'Payment Recovery has been successfully Allocate',
'form_ids' => $modelResult
);
}
Pass the ids to your controller for print
var ids = data.PaymentRecAllocation.form_ids.join(',');
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage?ids="+ids;
But in case of multiple inserts you should ideally use
$this->db->trans_start();
//all your insertion code here
//if anything breaks the db will be rollback
$this->db->trans_complete();

Retrieve data from database using ajax

I want to get data from database by using ajax. The data will be fetched by choosing the drop down option and click the search button and data will show up in the table. I've written the proper query and it runs very well. All I want is just show the data from database to the table with ajax. I've read tutorials and questions in Stackoverflow but still got no solution. Here's the sample of interface,
Here's my controller :
function getDataExcelKK() {
$station = $this->input->get('station');
$data = $this->M_dbstatmanagement->getDataExcelKK($station);
$this->load->view('v_lhastat_admin', $data);
}
The model :
function getDataExcelKK($station) {
$this->db->select("F.NAMA_FILE AS NAMA_FILE, DATE_FORMAT(F.TANGGAL_UPLOAD, '%d-%m-%Y %H:%i:%s') AS TANGGAL_UPLOAD");
$this->db->from("fileupload F");
$this->db->join("user U", "F.ID_USER = U.ID_USER");
$this->db->where("U.DOMISILI", $station);
$this->db->order_by("F.TANGGAL_UPLOAD DESC");
$query = $this->db->get();
return $query->result_array();
}
The view (table) :
<table class="table table-striped table-bordered table-hover table-condensed table-checkable order-column" id="lhaStatAdmin">
<thead>
<tr>
<th width="10%">No.</th>
<th width="10%">File Name</th>
<th width="10%">Upload Date</th>
</tr>
</thead>
<tbody id="isi-data">
<?php
$no = 1;
$i = 0;
foreach($getExcelFromKK as $key => $row) {?>
<tr>
<td><?php echo $no++;?></td>
<td><?php echo $row['NAMA_FILE'];?></td>
<td><?php echo $row['TANGGAL_UPLOAD'];?></td>
</tr>
<?php } ?>
</tbody>
</table>
And here's my ajax :
$('#button-search').on('click', function() {
var station = $('#stationChoose').val();
$.ajax({
async : true,
type : 'GET',
url : '<?php echo base_url();?>sms/getDataExcelKK',
data : {"station": station},
success :
function(data) {
$('#isi-data').html(data);
}
});
});
UPDATE : Instead of retrieve data into table, I got a table inside table when I click 'Search' button.
try those in your success in ajax
var preparedString = '';
for(var i=0;i<data.length;i++){
var preparedString += '<tr>'+
'<td>'+(i+1)+'</td>'+
'<td>'+data[i].NAMA_FILE+'</td>'+
'<td>'+data[i].TANGGAL_UPLOAD+'</td>'+
'</tr>'
}
$('#isi-data').append(preparedString);
so your ajax should look like this
$('#button-search').on('click', function() {
var station = $('#stationChoose').val();
$.ajax({
async : true,
type : 'GET',
url : '<?php echo base_url();?>sms/getDataExcelKK',
data : {"station": station},
success :
function(data) {
var preparedString = '';
for(var i=0;i<data.length;i++){
var preparedString += '<tr>'+
'<td>'+(i+1)+'</td>'+
'<td>'+data[i].NAMA_FILE+'</td>'+
'<td>'+data[i].TANGGAL_UPLOAD+'</td>'+
'</tr>'
}
$('#isi-data').append(preparedString);
}
});
});
Try this, keep url in double quotes.
$('#button-search').on('click', function() {
var station = $('#stationChoose').val();
$.ajax({
async : true,
type : 'GET',
url : "<?php echo base_url();?>sms/getDataExcelKK",
data : {"station": station},
success :
function(data) {
$('#isi-data').html(data);
}
});
});
you ether create the html from you data and append it(as #Ivan Tabaka sed) or you create your html in the PHP and append it in your html
is it possible to load full table in another view(ex.'table.php') and deposit this view on by replacing previous full table (can apply datatable in table.php) , after that for every table row become clickable to open modal, every tr become <tr onclick="action(3)">.
script:
function action(argument) {
// body...
alert(argument);
}
Try to set async to false.
$.ajax({
async : false,
type : 'GET',
url : "<?php echo base_url();?>sms/getDataExcelKK",
data : {"station": station},
success :
function(data) {
$('#isi-data').html(data);
}
});

Ajax request data could not show into the input field

I have created a loop which contains a dropdown list and input field.
What I need is:
When I select a value from dropdown list of Fruit Genres, the Unit Price field will display value come from database. I did all of these, but could not display value to the Unit Price field.
Here is my code:
View page:
<div class="table-responsive">
<table class="table table-hover" id="item-tbl">
<thead>
<tr>
<th class="text-center">Fruit Type</th>
<th class="text-center">Fruit Genres</th>
<th class="text-center">Qty</th>
<th class="text-center">Unit Price</th>
<th class="text-center">Sub Total</th>
</tr>
</thead>
<tbody>
<?php for($i=1; $i<=3; $i++){ ?>
<tr style="">
<td><?php echo $this->Form->input('fruit_type_id', ['options'=>$fruit_types, 'empty'=>'Select Fruit Type', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_type_id]']); ?></td>
<td><?php echo $this->Form->input('fruit_genre_id', ['options'=>$fruit_genres, 'empty'=>'Select Fruit Genre', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_genre_id]', 'class'=>'fruit_genre']); ?></td>
<td><?php echo $this->Form->input('quantity', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][quantity]', 'class'=>'quantity', 'id'=>'quantity_'.$i]); ?></td>
<td><?php echo $this->Form->input('price', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'price', 'id'=>'price_'.$i]); ?></td>
<td><?php echo $this->Form->input('sub_total', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'sub_total']); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var priceId = $(this).closest('tr').find('.price').attr('id');
// alert(priceId);
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// $(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
$(priceId).val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});
OrdersController.php
public function getFruitById($id){
$this->viewBuilder()->layout('ajax');
$this->loadModel('FruitGenres');
$item = $this->FruitGenres->get($id);
if (!empty($item)) {
$response['code'] = 200;
$response['message'] = 'DATA_FOUND';
$response['data'] = $item;
}else{
$response['code'] = 404;
$response['message'] = 'DATA_NOT_FOUND';
$response['data'] = array();
}
$this->set('response', $response);
$this->set('_serialize', ['response']);
}
I have got the expected data to the javascript console. but could not pass the data to the input field.
I have tried:
$(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
instead of
$(priceId).val(returnData.response.data.unit_price);
into the ajax success function, but it did not worked.
if I add a static id like the following:
$('#price_1').val(returnData.response.data.unit_price);
then it works.
Can anyone please help me? I am stuck on it.
I am using cakephp 3 for my project.
priceId is a value like price_1 without #. To make it a selector by id - prepend it with #:
$("#" + priceId).val(returnData.response.data.unit_price);
You can even simplify your code:
// you get id of the found element so as to find this element again
// you can store founded element instead of it's id
var priceDiv = $(this).closest('tr').find('.price');
// in success callback:
priceDiv.val(returnData.response.data.unit_price);
You can select the element directly instead of getting its ID and select with another jQuery call.
Another thing to note - this in the submit callback refer to the callback function itself, not the element.
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var $price = $(this).closest('tr').find('input.price'); // Get the element
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// Use $price directly as a jQuery object
$price.val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});

How to delete row in html based on cell value

I am trying to delete a row based on a table's cell value.
In my HTML page I have a simple search function. It would send the values in the text box to the database through ajax then PHP and then PHP would create a table dynamically based on what is in the database.
I have tried to check a the cell in the table for a specific value so that if it is true then the current row would be removed, the function name is checkMatch(). However it doesn't work.
This is the button in the HTML, the rest of the HTML is just a text box and drop down box:
<input type="button" id="device_search" value="Search" onclick="searchDevice(); checkMatch();"></input>
This is the function in the external JavaScript file:
function checkMatch()
{
var row = document.getElementById("thisRow");
var cell = Row.getElementById("match");
if(cell[0].innerText = "0%")
{
row.deleteRow(this);
}
}
And here's the creating of table in the PHP:
if($num_row)
{
echo "<table id=\"myTable\" border=\"1\">";
echo "<tr>
<th>Board ID</th>
<th>Tester Name</th>
<th>Board Name</th>
<th>Current Slot</th>
<th>Log Created</th>
<th>Required Slot</th>
<th>Match</th>
</tr>";
while($row = mysql_fetch_assoc($result))
{
$board_id = $row['board_id'];
$tester_name = $row['tester_name'];
$board_name = $row['board_name'];
$config = $row['config'];
$log_created = $row['log_created'];
$req_config = $row['configuration'];
$exploded = explode(",", $req_config);
$count = count($exploded);
$j = 0;
foreach($exploded as $value)
{
$number = strlen($value);
$arr = str_split($value, $number);
if(in_array($config, $arr))
{
$j += 1;
$j /= ($count / 100);
echo $j;
}
else
{
}
}
echo "<tr id = \"thisRow\">
<td>$board_id</td>
<td>$tester_name</td>
<td>$board_name</td>
<td>$config</td>
<td>$log_created</td>
<td>$req_config</td>
<td id = \"match\">$j%</td>
</tr>";
}
echo "</table>";
}
The column that I'm checking on is the last column which is the Match column. My idea is to remove that current row whenever the cell value of Match is 0%. I can't seem to find what's wrong with my codes, I'm not really good at manipulating DOM elements either so there must be some mistake. Any help on this? Or are there others ways, through PHP etc?
Note: I am not trying to delete the row from database. I just want to remove the row whenever Match is 0%.
EDIT, codes for searchDevice() in external js file:
function searchDevice()
{
var device_name = $("#device_name").val();
var tester_type = $("#tester_type").val();
var page = "database.php";
if(device_name==""||tester_type=="")
{
alert("Please do not leave any blanks.");
}
else
{
$.post(page, {
device_name : device_name,
tester_type : tester_type,
action : "search"
}, function(data) {
$("div#display_board").html(data);
checkMatch();
});
}
}
Currently my table does display with all the right values, but it doesn't remove the rows with 0%.
checkMatch() should be called at ajax success callback
id should be unique with in HTML document
PHP
// use `class` instead of `id`
echo "<tr class=\"thisRow\">
<td>$board_id</td>
<td>$tester_name</td>
<td>$board_name</td>
<td>$config</td>
<td>$log_created</td>
<td>$req_config</td>
<td class=\"match\">$j%</td>
</tr>";
Javascript
function checkMatch()
{
$("#myTable tr.thisRow").each(function() {
var thisRow = $(this);
var match = thisRow.find(".match");
// note the `==` operator
if(match.text() == "0%") {
thisRow.hide();
// OR thisRow.remove();
}
});
}

Best way to fetch a PHP array and output the result with jQuery?

I am trying to grab some text from a MyBB forum's exported messages. The file is a CSV file.
if (($handle = fopen("test.csv", "r")) === FALSE) {
exit("Couldn't load CSV");
}
fgetcsv($handle);
$messages = array();
$i = 0;
while($data = fgetcsv($handle)){
if(count($data) == 7){
$messages[$i]['date'] = $data[0] + "," + $data[1];
$messages[$i]['folder'] = $data[2];
$messages[$i]['subject'] = $data[3];
$messages[$i]['receiver'] = $data[4];
$messages[$i]['sender'] = $data[5];
$messages[$i]['message'] = str_replace("\'", "'", $data[6]);
}else{
$messages[$i]['date'] = $data[0];
$messages[$i]['folder'] = $data[1];
$messages[$i]['subject'] = $data[2];
$messages[$i]['receiver'] = $data[3];
$messages[$i]['sender'] = $data[4];
$messages[$i]['message'] = str_replace("\'", "'", $data[5]);
}
$i++;
}
I gave each tr and th tag (th includes the name of the sender and tr includes the message) a class with a number. First message is 0, second is 1, third is 2 and so on. I load the message in PHP like this:
$messages[0]['message'])
Where 0 is the first message. I want it to be like when I click on first message, it loads the first. When I click the second, it loads the second message. You get the idea.
My jQuery is as following:
$("td, th").on("click", function() {
var message = $(this).attr("class");
$("#message").text("<?= preg_replace("/\r|\n/", "", $messages[0]['message']) ?>");
});
I use preg_replace to get it all into one line.
Foreach loop
<table>
foreach($messages as $i => $message) {
echo <<<EOL
<tr>
<th class="$i"> {$message['sender']} </th>
</tr>
<tr>
<td class="$i"> {$message['message']} </td>
</tr>
EOL;
}
</table>
So to sum up: I want to display the message when I click the message in the table, but I am not sure what would be the best approach to do that.
$("td, th").on("click", function() {
var messageId = $(this).attr("class");
$.ajax({
url: "test.php",
type: "post",
data: messageId,
success: function(returnedVal){
$("#result").html(returnedVal);
},
error:function(){
$("#result").html('There is an error');
}
});
});
returnedVal is the value returned by your test.php.
For example, you can return your message.
Then you display it in $("#result") or wherever you want :)

Categories