Retrieve data from database using ajax - javascript

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);
}
});

Related

ajax tooltip doesn't load the data

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.

getting error while doing post request to another php page

So its a little bit complicated i will try to make it simple.
i have a table with 3 columns and i made function that if u press on the column its give u the id of the post.
after this i need the id so i can show the post over new page - post.php.
i made this request
$(".click_title").click(function() {
var $item = $(this).closest("tr").find(".post_id_c").text();// for sure work
$.post("post.php",{"post_id_to_show":$item},function(){
location.href = "post.php";
});
});
on the php i starting with this:
if (isset ($_POST["post_id_to_show"]) ){
$post_id_to_show = $_POST["post_id_to_show"];
}else{
echo "errror";
}
and now i getting an error from the echo thing.
and then i want to show the post from the sql table:
<table class="table">
<caption><h3 style="text-align:right">h1</h3></caption>
<tr class="success">
<th style="text-align:center"> h2
<th style="text-align:center"> h3
<th style="text-align:center"> h4
</tr>
<?php
$cursor = $MySQLdb->prepare("SELECT * FROM comments WHERE post_id=:post_id");
$cursor->execute( array(":post_id"=>$post_id_to_show) );
foreach ($cursor->fetchAll() as $obj): ?>
<tr>
<td style="text-align:center"> <? echo $obj['comment_data']?></td>
<td style="text-align:center"><? echo $obj['full_name']?></td>
<td style="text-align:center"><? echo $obj['date_time']?></td>
</tr>
<? endforeach; ?>
</table>
and i getting this error from the web page Notice: Undefined variable: post_id_to_show in /opt/lampp/htdocs/big_project/post.php on line 96
btw the line is this line
$cursor->execute( array(":post_id"=>$post_id_to_show) );
something wrong?
first i deliver the info by ajax like this.
$(".click_title").click(function(){
var $item = $(this).closest("tr").find(".post_id_c").text();//עובד בטוח
if($item){
$.ajax({
url: 'post.php',
type: 'POST',
data: {post_id_to_show:$item},
success: function(data) {
location.href = "post.php";
console.log(data); // Inspect this in your console
}
});
};
});
and than in the first call of post_id_to_show i switch it to session var.
in the second call i used the session var and it worked.

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');
});

Getting callback results to send to AJAX from php and update table

I am updating a database table via AJAX and PHP right now, but I want my page to be more responsive and update my table in my file after the data has been inserted into the database table.
I am not sure how to send info from my php file to AJAX and then how to get AJAX to update the table. How can I call back the data from my PHP file in order to make my table interactive?
The table
Current Announcements
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
while ($row = $announcements_stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
<?php
}
?>
}
</table>
<?php
}
}
AJAX
$(document).ready(function(){
$("#submit_announcement").on("click", function () {
var user_message = $("#announcement_message").val();
//$user = this.value;
$user = $("#approved_id").val();
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: {
"user_id": $user,
//"message": user_message
"user_message": user_message
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to get user info!");
alert(data);
} else {
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP file
$announcement_user_id= $_POST['user_id'];
$announcement_message= $_POST['user_message'];
$test = print_r($_POST, true);
file_put_contents('test.txt', $test);
//var_dump($announcement_user_id);
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('is', $announcement_user_id, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
//echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}
I think to do this, the following steps is what you need:
Write a new php script that gets the items form the database (like in 'the table' script) and echo these items in the table format you want. So when you call this script, it echo's only a table containing the rows.
Remove the dynamic rows part from the 'the table' script.
On success of your ajax request, make a new request to the new php script
Place the output of that script in the html using jQuery (.html(), insertAfter(), appendTo(), or anything like that).
`

I am not getting response from ajax request

I am getting no response from ajax request . i am posting a ajax call to processor.php file and the processor.php file is processing the file and sending the processed file back to javascript i am gerring my result in my console log but it is not showing in the html.
My javascript code is :
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$(".cart-show-product").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$(".cart-show-products").html(response);
}
});
}
and my php is :
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
{
$sql = mysqli_query($conn,
'SELECT * FROM
products_added
where
username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
and
item_added="'.mysqli_real_escape_string($conn, $_POST['item_name']).'"'
);
if(mysqli_num_rows($sql) < 1)
{
mysqli_query($conn,
"INSERT INTO products_added values(
'',
'".mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR'])."',
'".mysqli_real_escape_string($conn, $_POST['item_name'])."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."',
'".mysqli_real_escape_string($conn, '1')."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."'
'".mysqli_real_escape_string($conn, date("d-m-Y"))."')"
);
?>
<table class="cart-show-products">
<thead>
<tr>
<td>Sl.No</td>
<td>Item</td>
<td>Qty</td>
<td>Price</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
$sl_no = 1;
$sql = mysqli_query(
$conn,
'SELECT sum(amount) as grandtotal
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$grandtotal = strip_tags($row['grandtotal']);
$sql = mysqli_query(
$conn,
'SELECT
id,
item_added,
price,
quantity
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$item_id = strip_tags($row['item_id']);
$item_name = strip_tags($row['item_added']);
$item_price = strip_tags($row['price']);
$quantity = strip_tags($row['price']);
?>
<tr class="items_wrap items_wrap<?php echo $item_id; ?>">
<td><?php echo $sl_no++; ?></td>
<td><?php echo $item_name ?></td>
<td><?php echo $quantity ?></td>
<td><?php echo $item_price ?></td>
<td><i class="fa fa-times"></i></td>
</tr>
</tbody>
</table>
<?php
}
If you're getting a response in the console, then the issue must be with your HTML. I think part of the problem is you've created a section on the HTML page wiht a class that is the same as the table the AJAX call is bringing into the page. I would suggest changing the HTML element to us an ID instead. Something like
<div id="products-table"></div>
And then change your JavaScript to
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$("#products-table").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$("#products-table").html(response);
}
});
}
If you stay with the class names you've used, subsequent updates are going to have problems because you'll have 2 elements on the page with the same class. Your script could potentially be confused about which one to change.
If this is your actual code, then you have a syntax error in your PHP file. There are a missing close bracket for:
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
The second problem is, you are not print anything, if this condition has failed.
Note
You do not need to use isset, if you are checking empty. empty will return false, if the variable not set.
You can debug your respons by check NET tab in your web developer tools, or see, what is the response of the AJAX.

Categories