I am having a table with data from database called through codeigniter controller.What I want to do is read the selected value from within the table send it back to the controller and use those values to retrieve new records from DB and then load them on again into the page.
My Controller:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Dashboard1 extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('dash_match_model');
$this->session->keep_flashdata('supplier_id');
$this->load->helper('url');
$this->load->database();
}
public function index() {
$arr['page']='dash1';
$arr['present_all_suppliers'] = $this->dash_match_model->dash_present_all_suppliers();
$arr['supplierCompany'] = "";
$this->load->view('clients/clDashboard',$arr);
}
public function select_supplier() {
$supplierCompany = $this->input ->post('supplierCompany');
$arr['present_all_suppliers'] = $this->dash_match_model->dash_present_all_suppliers();
$arr['supplierCompany'] = $supplierCompany;
$supplier_selected = $this->user_model->return_selected_supplier($supplierCompany);
foreach($supplier_selected->result() as $row)
{
$this->session->set_flashdata('supplier_id', $row->supplier_id);
}
$this->load->view('unspscSegment',$arr);
}
}
Specific lines of table of my view file:
<table id="suppliertable" class="table table-striped table-bordered bootstrap-datatable datatable">
<thead>
<tr>
<th>Supplier</th>
<th>Open Range</th>
<th>Fill Content</th>
<th>Total Match</th>
</tr>
</thead>
<tbody>
<?php foreach ($present_all_suppliers as $v): ?>
<tr>
<td onclick="window.location = 'http://example.com'" class="center" style="color:#0c595b;"> <?php echo $v->supplierCompany; ?> </td>
<td class="center"></td>
<td class="center"></td>
<td class="center"></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
How can I do that with javascript so when i select a supplier (value) to get the selected value and sent it to the controller? Then what should I modify to the controller in order to send the value to the model and collect it and reload them in the view?
You can use jQuery.ajax()
Implemented in your code:
Script:
<script>
$(".supplier_edit").click(function(){
var supplier_company = $(this).find('input').val()
$.ajax({
type: 'POST',
url: 'http://example.com/'+'Dashboard1/select_supplier',
data: {supplierCompany: supplier_company},
success: function(result) {
$("#content").html(result)
}
})
return false
})
</script>
HTML:
<tbody>
<?php foreach ($present_all_suppliers as $v): ?>
<tr>
<td class="supplier_edit" style="color:#0c595b;"><input type="hidden" value="<?php echo $v->supplierCompany; ?>" ></td>
<td class="center"></td>
<td class="center"></td>
<td class="center"></td>
</tr>
<?php endforeach; ?>
</tbody>
<div id="content">content from the controller</div>
Related
I have a table which shows the list of my products and I have used jQuery to delete products without reloading the page, however the updated table doesn't show unless I refresh the page..
I have tried to hide it by using opacity, still it doesn't work..
Here is my php code
<div class="table-stats order-table ov-h">
<table id="bootstrap-data-table" class="table ">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<?php
$stmt_1 = mysqli_prepare($link,"SELECT * FROM products");
mysqli_stmt_execute($stmt_1);
$result = mysqli_stmt_get_result($stmt_1);
while($row = mysqli_fetch_array($result)){ ?>
<div class="product">
<tr class="product">
<?php
$sql_img = "SELECT * FROM pro_images WHERE pro_id= ? LIMIT ?";
$stmt_img = mysqli_prepare($link, $sql_img);
mysqli_stmt_bind_param($stmt_img, "ii" ,$param_pro_id, $param_limit);
$param_pro_id = $row["pro_id"];
$param_limit = 1;
mysqli_stmt_execute($stmt_img);
$img_results = mysqli_stmt_get_result($stmt_img);
$image = mysqli_fetch_assoc($img_results);
?>
<td><img src="../admin/assets/img/products/<?php echo $image["pro_image"]; ?>"></td>
<td><?php echo $row["pro_name"]; ?></td>
<td><?php echo $row["pro_quantity"]; ?></td>
<?php
$sql_category = "SELECT cat_name FROM categories WHERE cat_id = ?";
$stmt_category = mysqli_prepare($link, $sql_category);
mysqli_stmt_bind_param($stmt_category, "i", $param_cat_id);
$param_cat_id = $row["pro_category"];
mysqli_stmt_execute($stmt_category);
$result_category = mysqli_stmt_get_result($stmt_category);
$category = mysqli_fetch_assoc($result_category);
?>
<td> <?php echo $category["cat_name"]; ?> </td>
<?php
$pro_ord = "SELECT COUNT(*) AS total FROM order_details WHERE pro_id = ?";
$pro_stmt = mysqli_prepare($link, $pro_ord);
mysqli_stmt_bind_param($pro_stmt ,"i", $row["pro_id"]);
mysqli_stmt_execute($pro_stmt);
$pro_res = mysqli_stmt_get_result($pro_stmt);
$pro = mysqli_fetch_array($pro_res);
?>
<td><?php echo $pro["total"]; ?></td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data(<?php echo $row["pro_id"]; ?>)"><i class="ti-trash"></i></button>
</td>
</tr>
</div>
<?php } ?>
</tbody>
</table>
</div>
And here is my JQUERY code
function delete_data(d){
var id=d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
$.ajax({
type: "post",
url: "products.php",
data: {id:id},
success: function(){
$(this).parents(".product").animate("fast").animate({ opacity : "hide" }, "slow");
}
});
}
}
And here is the delete code
$pro_id =$_POST['id'];
$delete = "DELETE FROM products WHERE pro_id= ?";
$results = mysqli_prepare($link, $delete);
mysqli_stmt_bind_param($results, "i", $param_pro_id);
$param_pro_id = $pro_id;
mysqli_stmt_execute($results);
You need to be more specific when you targeting the div you want to refresh, for example:
success: function(){
$("#div_id_you_want_refresh")
.load("your_entire_url" + "#div_id_you_want_refresh");
}
You can pass this as well inside your delete_data function where this refer to current element clicked i.e : your button . Then , inside success function use this to hide your .product element.
Demo Code:
function delete_data(d, el) {
var id = d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
/* $.ajax({
type: "post",
url: "products.php",
data: {
id: id
},
success: function() {*/
//use this then remove closest product tr
$(el).closest(".product").animate("fast").animate({
opacity: "hide"
}, "slow");
/* }
});*/
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="bootstrap-data-table" class="table">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
1
</td>
<td>
abs
<td>
1222
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<!--pass `this` inside fn-->
<button class="remove badge badge-danger" onclick="delete_data('1',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
12
</td>
<td>
abs1
<td>
12221
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data('2',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
</tbody>
</table>
I have a normal html table filled with database entries.
I got a plugin to select multiple rows in this table.
Now i want to click on a button and delete the database entry so I need to get the id out of the array and but it in my php script.
But I have not really an idea how to do it.
</div>
<table id="myTable" class="content-table">
<thead>
<tr>
<th>ID</th>
<th>Artikelnummer</th>
<th>Name</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM artikel;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td> <?php echo $row["id"]?></td> <?php
?> <td> <?php echo $row["artikelnummer"]?></td> <?php
?> <td> <?php echo $row["name"]?></td> <?php
?> <td> <?php echo $row["preis"]?> €</td> </tr><?php
}
}
?>
</tbody>
</table>
</div>
var $rows = [];
$(function() {
console.log( "ready!" );
// start plugin
$('#myTable').TableSelection({
sort : true, // sort or not (true | false)
status : 'multiple', // single or multiple selection (default is 'single')
}, function(obj){ // callback function return selected rows array
$rows = obj.rows;
});
});
<?php
include_once 'dbh.inc.php';
$artid = ???;
$sql = "DELETE FROM artikel WHERE id= $artid;";
mysqli_query($conn, $sql);
header("Location: ../index.php?daten=success");
You can do it with html attributes. I make a example for you with html, css and javascript.
this is your html.
<table id="tableSelected" class="content-table">
<thead>
<tr>
<th>ID</th>
<th>Artikelnummer</th>
<th>Name</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<tr data-id="1">
<td>1</td>
<td>1-1</td>
<td>Test</td>
<td>1</td>
</tr>
<tr data-id="2">
<td>2</td>
<td>2-1</td>
<td>Foo</td>
<td>1</td>
</tr>
</tbody>
</table>
as you can see, every "tr" tag has "data-id" attribute.
var $rows = [];
$(function() {
$('#tableSelected').TableSelection({
sort : true,
status : 'multiple',
}, function(obj) {
$.each(obj.rows, function(i, row){
var id = $('#tableSelected').RowValue(row).attr('data-id') // You can get id with this code
});
});
});
Note: https://codepen.io/yusufilkeroguz/pen/vqPgzZ you can see live preview from here :)
I tried to update 1 row in table with ajax triggered by onchange dropdown, I succeed update data but it updating all data in my table.
so how I can get unique value (eg :User ID) to pass it from ajax to my php so i can update it only 1 row?
here's my code :
my table (transactions.php)
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>User ID</th>
<th>Pengirim</th>
<th>Jumlah Transfer</th>
<th>Berita Acara</th>
<th>Status</th>
<th>Rincian</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($koneksi, "select * from konf_transf order by tanggal desc limit 7 ");
while($data1 = mysqli_fetch_array($query)){
?>
<tr>
<td>
<center><?php echo $data1['usr_id']; ?></center>
</td>
<td>
<center><?php echo $data1['nm_pengirim']; ?></center>
</td>
<td>
<center>Rp. <?php echo number_format($data1['jmlh_transf'],0,'','.'); ?>,-</center>
</td>
<td>
<center><?php echo $data1['berita_acara']; ?></center>
</td>
<td>
<center><?php echo $data1['status']; ?></center>
</td>
<td>
<center>
<select name="pilihstatus" id="pilihstatus" onchange="updatetransactions();">
<option value="Pilihan">Pilihan</option>
<option value="Sudah">Sudah</option>
<option value="Belum">Belum</option>
</select>
</center>
</td>
</tr>
<?php } ?>
</tbody>
</table>
and here my ajax
function updatetransactions(){
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"updatestatustransaksi.php",
data:"status="+id,
success:function(data){
alert('Successfully updated mysql database');
}
});
}
my updatestatustransaksi.php
<?php
require_once("koneksi.php");
session_start();
if (!isset($_SESSION['username'])) {
echo "<script>alert('You must register an account first, we will redirect you to register page !'); window.location = 'registuser.php'</script>";
}
$dataupd = $_POST["status"];
$query = mysqli_query($koneksi, "UPDATE `konf_transf` SET `status` = '$dataupd' WHERE `id` = '$penjualan_id'");
if ($query) {
echo "<script>alert('Update Success.'); window.location = 'transactions.php' </script>";
} else {
echo "<script>alert('Update Failure.'); window.location = 'transactions.php' </script>";
}
I assume that you update all of your rows in your database, with no WHERE condition. In your script, lets also get the corresponding id of that row in your database.
Lets assign first the id for each table row:
while($data1 = mysqli_fetch_array($query)){
?>
<tr id="<?=($data1['user_id'])?>">
Then, lets change how you trigger your javascript. Lets first change the <select> field:
<select name="pilihstatus" id="pilihstatus" class="pilihstatus">
Then, get the corresponding id using the script below:
$(".pilihstatus").change(function(){
var elem = $(this),
selecteditem = elem.val(),
id = elem.closest('tr').attr('id');
$.ajax({
type:"post",
url:"updatestatustransaksi.php",
data: {'status':selecteditem, 'id':id},
success:function(data){
alert('Successfully updated mysql database');
}
});
});
And on your updatestatustransaksi.php file (please use prepared statement):
$stmt = $koneksi->prepare("UPDATE `konf_transf` SET `status` = ? WHERE `id` = ?");
$stmt->bind_param("si", $_POST['selecteditem'], $_POST['id']);
$stmt->execute();
$stmt->close();
Try adding data_id attribute to select
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>User ID</th>
<th>Pengirim</th>
<th>Jumlah Transfer</th>
<th>Berita Acara</th>
<th>Status</th>
<th>Rincian</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($koneksi, "select * from konf_transf order by tanggal desc limit 7 ");
while($data1 = mysqli_fetch_array($query)){
?>
<tr>
<td>
<center><?php echo $data1['usr_id']; ?></center>
</td>
<td>
<center><?php echo $data1['nm_pengirim']; ?></center>
</td>
<td>
<center>Rp. <?php echo number_format($data1['jmlh_transf'],0,'','.'); ?>,-</center>
</td>
<td>
<center><?php echo $data1['berita_acara']; ?></center>
</td>
<td>
<center><?php echo $data1['status']; ?></center>
</td>
<td>
<center>
<select name="pilihstatus" id="pilihstatus" onchange="updatetransactions();" data_id='<?php echo $data1['usr_id']; ?>'>
<option value="Pilihan">Pilihan</option>
<option value="Sudah">Sudah</option>
<option value="Belum">Belum</option>
</select>
</center>
</td>
</tr>
<?php } ?>
</tbody>
</table>
and get that data_id value in your function
function updatetransactions(){
var status = $('select option:selected').text();
var status = $('select').attr('data_id');
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"updatestatustransaksi.php",
data:{'status'=status,'id'=id}
success:function(data){
alert('Successfully updated mysql database');
}
});
}
and at your updatestatustransaksi.php
<?php
require_once("koneksi.php");
session_start();
if (!isset($_SESSION['username'])) {
echo "<script>alert('You must register an account first, we will redirect you to register page !'); window.location = 'registuser.php'</script>";
}
$dataupd = $_POST["status"];
$id = $_POST["id"];
$query = mysqli_query($koneksi, "UPDATE `konf_transf` SET `status` = '$dataupd' WHERE `id` = '$id'");
if ($query) {
echo "<script>alert('Update Success.'); window.location = 'transactions.php' </script>";
} else {
echo "<script>alert('Update Failure.'); window.location = 'transactions.php' </script>";
}
Have you initialised $penjualan_id? I think you need to initialise it like this:
$penjualan_id=$_SESSION['user_id']
I'm having some problems with auto refreshing my div, using code igniter framework. What I'm trying to do in the code below is to auto refresh the particular div id="lot_info" every 1 second.
The div is not refreshing and I am getting an error at google chrome's console saying: jquery.js:5 GET http://mywebsite/Home/display_lot_table 404 (Not Found)
Controller:
public function index()
{
$data['title'] = 'Test System';
$view = 'view';
$this->load->view('templates/normal_header', $data);
$this->load_lot_table($view);
$this->load->view('templates/legend_footer', $data);
}
public function load_lot_table($type)
{
$config = array();
$config['base_url'] = base_url()."index.php/Home/index";
$config['total_rows'] = $this->home_model->record_count();
$config['per_page'] = 10;
$config['uri_segment'] = 3;
$config['next_link'] = 'Next';
$config['prev_link'] = 'Previous';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$results = $this->home_model->fetch_lots($config['per_page'], $page);
$data['disp_rows'] = $results;
$data['links'] = $this->pagination->create_links();
if($type == 'view')
{
return $this->load->view('home/index', $data);
}
elseif($type == 'refresh')
{
return $this->load->view('home/index', $data, true);
}
}
public function display_lot_table()
{
$refresh = 'refresh';
$this->load_lot_table($refresh);
}
View:
<script>
$(document).ready(function()
{
refresh();
});
function refresh()
{
setTimeout(function()
{
$('#lot_info').load('<?php echo base_url();?>Home/display_lot_table');
refresh();
}, 1000);
}
</script>
<div id="lot_info" class="container">
<table class="table table-responsive table-condensed table-bordered dispo-table">
<tr>
<th rowspan="2">AStatus</th>
<th rowspan="2">A</th>
<th rowspan="2">B</th>
<th rowspan="2">C</th>
<th rowspan="2">D</th>
<th rowspan="2">E</th>
<th rowspan="2">F</th>
<th colspan="3" scope"col">G</th>
<th rowspan="2">H</th>
</tr>
<tr>
<th>I</th>
<th>J</th>
<th>K</th>
</tr>
<?php foreach($disp_rows as $row):?>
<tr>
<td><?php echo $row->Astatus;?></td>
<td align="center"><?php echo $row->B;?></td>
<td align="center"><?php echo $row->C;?></td>
<td align="center"><?php echo $row->D;?></td>
<td align="center"><?php echo $row->E;?></td>
<td align="center"><?php echo $row->F;?></td>
<td align="center"><?php echo $row->G;?></td>
<td><?php echo $row->H;?></td>
<td align="center"><?php echo $row->I;?></td>
<td align="center">-</td>
<td align="center"><?php echo $row->J;?></td>
</tr>
<?php endforeach?>
</table>
</div>
You received error :
jquery.js:5 GET http://mywebsite/Home/display_lot_table 404 (Not Found)
Seems like the path url is not correct. Look closely, is that correct? cause i see you defined in controller method having code like $config['base_url'] = base_url()."index.php/Home/index";. Completely different with the code defined in jquery load as $('#lot_info').load('<?php echo base_url();?>Home/display_lot_table');. So why not adding index.php like below code :
$('#lot_info').load('<?php echo base_url();?>index.php/Home/display_lot_table');
You can remove those index.php from url anyway.
Hello I am wanting to echo a PHP Variable to a buttons value then send the buttons value to an input text. I was able to echo the button with the variable but when I click the button it does nothing. I'm not sure why, because when I do this without the PHP just the script, and inputs it works perfectly. I am just missing something I know it, I can't find much info on how to pass php to a button then pass the button value to an input text.
Here's the script that passes the button value to the input text:
$( document ).ready(function() {
var $theButtons = $(".button");
var $theinput = $("#theinput");
$theButtons.click(function() {
$theinput.val(this.value);
});
});
Here's the PHP that echos the variable as a button:
require "config.php"; // database connection
$in=$_GET['txt'];
if(!ctype_alnum($in)){ //
echo "Search By Name, or Entry ID";
exit;
}
$msg="";
$msg="";
if(strlen($in)>0 and strlen($in) <20 ){
$sql="select name, entry, displayid from item_template where name like '%$in%' LIMIT 10"; // the query
foreach ($dbo->query($sql) as $nt) {
//$msg.=$nt[name]."->$nt[id]<br>";
$msg .="<table style='table-layout:fixed;'> // Just the start of my table
<tr>
<td>Name</td>
<td>Entry ID</td>
<td>Display ID</td>
</tr>
<tr>
<td align=center><a href=http://wowhead.com/item=$nt[entry]>
$nt[name]</a>
</td>
<td>$nt[entry]</td>
<td>
<input type=button class=button value=$nt[displayid]> // The Value I need echoed out in a button is $nt[displayid]
</td>
</tr>
</table>"; // end of my table}
}
$msg .='';
echo $msg;
Not that it matters but here is the input text
<input type="text" id="theinput"/>
Make it easy on yourself and try to make your code easy to read. I personally prefer to write my html cleanly and outside of echo statements like so:
Html
if (strlen($in) > 0 and strlen($in) < 20) {
$sql = "select name, entry, displayid from item_template where name like '%{$in}%' LIMIT 10"; // the query
foreach ($dbo->query($sql) as $nt) {
//$msg.=$nt[name]."->$nt[id]<br>";
?>
<table style="table-layout:fixed;">
<tr>
<td>Name</td>
<td>Entry ID</td>
<td>Display ID</td>
</tr>
<tr>
<td align="center">
<?=$nt['name'];?>
</td>
<td><?=$nt['entry'];?></td>
<td>
<input type="button" class="button" value="<?=$nt['displayid'];?>">
</td>
</tr>
</table>
<?php
}
}
Javascript
$( document ).ready(function() {
var $theButtons = $(".button");
var $theinput = $("#theinput");
$theButtons.click(function() {
// $theinput is out of scope here unless you make it a global (remove 'var')
// Okay, not out of scope, but I feel it is confusing unless you're using this specific selector more than once or twice.
$("#theinput").val(jQuery(this).val());
});
});
Ok, here goes...
Use event delegation in your JavaScript to handle the button clicks. This will work for all present and future buttons
jQuery(function($) {
var $theInput = $('#theinput');
$(document).on('click', '.button', function() {
$theInput.val(this.value);
});
});
Less important but I have no idea why you're producing a complete table for each record. I'd structure it like this...
// snip
if (strlen($in)>0 and strlen($in) <20 ) :
// you really should be using a prepared statement
$sql="select name, entry, displayid from item_template where name like '%$in%' LIMIT 10";
?>
<table style="table-layout:fixed;">
<thead>
<tr>
<th>Name</th>
<th>Entry ID</th>
<th>Display ID</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbo->query($sql) as $nt) : ?>
<tr>
<td align="center">
<?= htmlspecialchars($nt['name']) ?>
</td>
<td><?= htmlspecialchars($nt['entry']) ?></td>
<td>
<button type="button" class="button" value="<?= htmlspecialchars($nt['displayid']) ?>"><?= htmlspecialchars($nt['displayid']) ?></button>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php endif;