codeigniter ajax cart update quantity - php

I am new to codeigniter and ajax. I can add item to cart and remove it as well. but when i am trying to update the quantity of the first row it works fine. but if i change the quantity of other rows and when i leave the mouse it updates the price * quanity, but it wont take the quantity what we enterd instead it takes the value of the first row quantity. can anyone please help me out.
view file :
<html>
<head>
<title>Codeigniter Shopping Cart with Ajax JQuery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br /><br />
<div class="col-lg-6 col-md-6">
<div class="table-responsive">
<h3 align="center">Codeigniter Shopping Cart with Ajax JQuery</h3><br />
<?php
foreach($product as $row)
{
echo '
<div class="col-md-4" style="padding:16px; background-color:#f1f1f1; border:1px solid #ccc; margin-bottom:16px; height:400px" align="center">
<img src="'.base_url().'images/'.$row->product_image.'" class="img-thumbnail" /><br />
<h4>'.$row->product_name.'</h4>
<h3 class="text-danger">$'.$row->product_price.'</h3>
<input type="text" name="quantity" class="form-control quantity" id="'.$row->product_id.'" /><br />
<button type="button" name="add_cart" class="btn btn-success add_cart" data-productname="'.$row->product_name.'" data-price="'.$row->product_price.'" data-productid="'.$row->product_id.'" />Add to Cart</button>
</div>
';
}
?>
</div>
</div>
<div class="col-lg-6 col-md-6">
<div id="cart_details">
<h3 align="center">Cart is Empty</h3>
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.add_cart').click(function(){
var product_id = $(this).data("productid");
var product_name = $(this).data("productname");
var product_price = $(this).data("price");
var quantity = $('#' + product_id).val();
if(quantity != '' && quantity > 0)
{
$.ajax({
url:"<?php echo base_url(); ?>shopping_cart/add",
method:"POST",
data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
success:function(data)
{
alert("Product Added into Cart");
$('#cart_details').html(data);
$('#' + product_id).val('');
}
});
}
else
{
alert("Please Enter quantity");
}
});
$('#cart_details').load("<?php echo base_url(); ?>shopping_cart/load");
// $(document).ready(function(){
// $("input").blur(function(e){
// e.preventDefault();
// }).blur(function() {
// alert("opo");
// });
// });
$(document).on('mouseleave', '#myqty', function(){
var rowid = $(this).attr("class");
var product_price = $(this).attr("title");
//var proqty = $('#myqty').val();
var fieldId = $(this).attr("class");
var proqty = $('#myqty').val();
alert(proqty);
$.ajax({
url:"<?php echo base_url();?>shopping_cart/update",
method:"POST",
data : {rowid:rowid,proqty:proqty,product_price:product_price},
//data: "rowid="+rowid+"&proqty="+proqty+"&product_price="+product_price,
success:function(data)
{
$('#cart_details').html(data);
}
});
});
$(document).on('click', '.remove_inventory', function(){
var row_id = $(this).attr("id");
if(confirm("Are you sure you want to remove this?"))
{
$.ajax({
url:"<?php echo base_url(); ?>shopping_cart/remove",
method:"POST",
data:{row_id:row_id},
success:function(data)
{
alert("Product removed from Cart");
$('#cart_details').html(data);
}
});
}
else
{
return false;
}
});
$(document).on('click', '#clear_cart', function(){
if(confirm("Are you sure you want to clear cart?"))
{
$.ajax({
url:"<?php echo base_url(); ?>shopping_cart/clear",
success:function(data)
{
alert("Your cart has been clear...");
$('#cart_details').html(data);
}
});
}
else
{
return false;
}
});
});
</script>
controller file :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Shopping_cart extends CI_Controller {
function index()
{
$this->load->model("shopping_cart_model");
$data["product"] = $this->shopping_cart_model->fetch_all();
$this->load->view("shopping_cart", $data);
}
function add()
{
$this->load->library("cart");
$data = array(
"id" => $_POST["product_id"],
"name" => $_POST["product_name"],
"qty" => $_POST["quantity"],
"price" => $_POST["product_price"]
);
$this->cart->insert($data); //return rowid
echo $this->view();
}
function load()
{
echo $this->view();
}
function remove()
{
$this->load->library("cart");
$row_id = $_POST["row_id"];
$data = array(
'rowid' => $row_id,
'qty' => 0
);
$this->cart->update($data);
echo $this->view();
}
function clear()
{
$this->load->library("cart");
$this->cart->destroy();
echo $this->view();
}
function view()
{
$this->load->library("cart");
$output = '';
$output .= '
<h3>Shopping Cart</h3><br />
';
echo count($this->cart->contents());
$output .= '
<div class="table-responsive">
<div align="right">
<button type="button" id="clear_cart" class="btn btn-warning">Clear Cart</button>
</div>
<br />
<table class="table table-bordered">
<tr>
<th width="40%">Name</th>
<th width="15%">Quantity</th>
<th width="15%">Price</th>
<th width="15%">Total</th>
<th width="15%">Action</th>
</tr>
';
$count = 0;
foreach($this->cart->contents() as $items)
{
$count++;
$output .= '
<tr>
<td>'.$items["name"].'</td>
<td><input id="myqty" title="'.$items["price"].'" class="'.$items['rowid'].'" type="number" min="1" value="'.$items['qty'].'">
</td>
<td><span id='.$items["price"].'>'.$items["price"].'</span></td>
<td>'.$items["subtotal"].'</td>
<td><button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="'.$items["rowid"].'">Remove</button></td>
</tr>
';
}
$output .= '
<tr>
<td colspan="4" align="right">Total</td>
<td><span>'.$this->cart->total().'</span></td>
</tr>
</table>
</div>
';
if($count == 0)
{
$output = '<h3 align="center">Cart is Empty</h3>';
}
return $output;
}
function update(){
$this->load->library("cart");
// Recieve post values,calcute them and update
$rowid = $_POST['rowid'];
$price = $_POST['product_price'];
$qty = $_POST['proqty'];
$data = array(
'rowid' => $rowid,
'price' => $price,
'qty' => $qty
);
$this->cart->update($data);
echo $this->view();
}
}

<input class="qty_set" name="quantity" data-rowid="your rowid" type="number" value="5">
this will not work "quantity = document.getElementById ("qty_set"). value;"
// use this var quantity = $(this).val();
$(document).on('change', '.qty_set', function(){
var quantity = $(this).val();
var row_id = $(this).data("rowid");
$.ajax({
url:"<?php echo base_url(); ?>Sepet/setliste",
method:"POST",
data:{row_id:row_id, quantity:quantity},
success:function(data)
{
//alert("Güncellendi");
$('#sepetload').html(data);
}
});

Related

Button Submit Inside Serverside Table Codeigniter

I have datatables contain input box and button for each row data, for sure form was added outside table tag, but i have issue while clicking on button submit inside that table, the button did not work well and no appear anything error logs
My Controller.php for displaying row:
public function tagihankost()
{
$list = $this->tagihan->get_datatables();
$data = array();
foreach ($list as $tagih) {
$row = array();
$format = number_format($tagih->harga, '0', '', '.');
$row[] = "<input type='text' value='$tagih->bulan' id='bulan' class='rowtagihan' form='payment-form' readonly>";
$row[] = "<input type='number' value='$format' id='harga' class='rowtagihan' form='payment-form' readonly>";
if ($tagih->status == 200) {
$row[] = "<span class='badge bg-success' style='color:white'>Lunas</span>";
} elseif ($tagih->status == 201) {
$row[] = "<span class='badge bg-warning' style='color:black'>Pending</span>";
} else {
$row[] = "<span class='badge bg-danger' style='color:white'>Belum Bayar</span>";
};
$row[] = "<button id='pay-button'>Pay!</button>";
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->tagihan->count_all(),
"recordsFiltered" => $this->tagihan->count_filtered(),
"data" => $data,
);
echo json_encode($output);
}
My View.php :
<div class="card bodycontent">
<div class="card-body">
<div class="tab-pane table-responsive">
<table id="tablekost" class="table table-striped table-bordered" width="100%" cellspacing="0">
<thead>
<tr>
<td>Bulan</td>
<td>Tagihan</td>
<td>Status</td>
<td>#</td>
</tr>
</thead>
<form id="payment-form" method="post" action="<?= site_url() ?>/snap/finish">
<input type="hidden" name="result_type" id="result-type" value="">
<input type="hidden" name="result_data" id="result-data" value="">
</form>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
And the last thing is my JS:
<script type="text/javascript">
$('#pay-button').click(function(event) {
event.preventDefault();
$(this).attr("disabled", "disabled");
$.ajax({
url: '<?= site_url() ?>/snap/token',
cache: false,
success: function(data) {
//location = data;
console.log('token = ' + data);
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
function changeResult(type, data) {
$("#result-type").val(type);
$("#result-data").val(JSON.stringify(data));
//resultType.innerHTML = type;
//resultData.innerHTML = JSON.stringify(data);
}
snap.pay(data, {
onSuccess: function(result) {
changeResult('success', result);
console.log(result.status_message);
console.log(result);
$("#payment-form").submit();
},
onPending: function(result) {
changeResult('pending', result);
console.log(result.status_message);
$("#payment-form").submit();
},
onError: function(result) {
changeResult('error', result);
console.log(result.status_message);
$("#payment-form").submit();
}
});
}
});
});
So what i have missed?

how to search a username in php ajax

hey guys I need some help please guide me where I am doing wrong in coding. This is table of showing record of users
I want pagination operation and search operation on my index.php file. Pagination is working but when I am type a single letter (example: a or Haris) on search bar then show me message that data not found this is message showing when type a username on search bar
This my ajax function that on index.php file I am pagination or search
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#message').keyup(function(){
var srch = $(this).val();
if(srch != '')
{
load_data(srch);
}
else
{
load_data();
}
});
function load_data(page)
{
$.ajax({
url:"search.php",
method:"GET",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
This my search.php file
<?php
include("common/config.php");
$output = '';
if(isset($_POST["query"]))
{
$search = $_POST["query"];
$where = "id LIKE '%".$search."%'
OR name LIKE '%".$search."%'
OR email LIKE '%".$search."%'
OR phone LIKE '%".$search."%'";
$query = $db->select(array("*"),"user","$where","","id desc","");
}
else
{
$limit = 5;
$page = '';
if (isset($_GET["page"] ))
{
$page = $_GET["page"];
}
else
{
$page=1;
}
$record_index= ($page-1) * $limit;
$query = $db->select(array("*"),PREFIX."user", "", "", "id desc", "$record_index, $limit");
}
if($query)
{
$output .= '
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th style="text-align: center !important;"><input type="checkbox" name="select_all" id="select_all" value=""/></th>
<th style="text-align: center !important;">ID</th>
<th style="text-align: center !important;">Name</th>
<th style="text-align: center !important;">Email</th>
<th style="text-align: center !important;">Phone</th>
<th colspan="4" style="text-align: center !important;">Action</th>
</tr>
';
foreach($query as $row)
{
$output .= '
<tr align="center">
<td align="center"><input type="checkbox" name="checked_id[]"
class="checkbox" value="'.$row->id.'"/></td>
<td>'.$row->id.'</td>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->phone.'</td>
<td>Edit</td>
<td><a onclick="return confirm(\'Are you sure to delete?\')"
href="del.php?del='.$row->id.'">Delete</a></td>
</tr>';
}
$output .= '</table><br /><div align="center">';
$total_pages = ceil($db->countfields("*","user") / $limit);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
}
else
{
echo 'Data Not Found';
}
?>
When I am change the name of function,pagination is working but its still search a user record not working.
<script>
$(document).ready(function(){
load_data_1();
load_data_2();
function load_data_1(query)
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#message').keyup(function(){
var srch = $(this).val();
if(srch != '')
{
load_data(srch);
}
else
{
load_data_1();
}
});
function load_data_2(page)
{
$.ajax({
url:"search.php",
method:"GET",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data_2(page);
});
});
</script>
I don't see from your code what "PREFIX" is, but in the search query it is missing while it is present in the pagination query. Hope it helps

Trying to display live table which is editable using ajax and php

I have four different files
index.php
select.php
insert.php
edit.php
delete.php
In my backend I have created a database named 'ecc'
Database 'ecc' has atable named 'task'
The table task has following fields
id, name, category, cost
Datatype for id set to int and index as primary also id field is on auto increment
My Issue:My code is only displaying 'Live Table Data'.
It would be grate if someone rewrite it or suggest some changes.
index.php
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Live Table Add Edit Delete using Ajax Jquery in PHP Mysql</h3><br />
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
var name = $('#name').text();
var category = $('#category').text();
var cost = $('#cost').text();
if(name == '')
{
alert("Enter Service Name");
return false;
}
if(category == '')
{
alert("Enter Category of Service");
return false;
}
if(cost == '')
{
alert("Enter cost");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{name:name, category:category, cost:cost},
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
function edit_data(id, text, column_name)
{
$.ajax({
url:"edit.php",
method:"POST",
data:{id:id, text:text, column_name:column_name},
dataType:"text",
success:function(data){
alert(data);
}
});
}
$(document).on('blur', '.name', function(){
var id = $(this).data("id1");
var name = $(this).text();
edit_data(id, name, "name");
});
$(document).on('blur', '.category', function(){
var id = $(this).data("id2");
var category = $(this).text();
edit_data(id,category, "category");
$(document).on('blur', '.cost', function(){
var id = $(this).data("id3");
var category = $(this).text();
edit_data(id,cost, "cost");
});
$(document).on('click', '.btn_delete', function(){
var id=$(this).data("id4");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
</script>
select.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ecc");
$output = '';
$sql = "SELECT * FROM task ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">First Name</th>
<th width="40%">Last Name</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="name" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
<td class="category" data-id2="'.$row["id"].'" contenteditable>'.$row["category"].'</td>
<td class="cost" data-id3="'.$row["id"].'" contenteditable>'.$row["cost"].'</td>
<td><button type="button" name="delete_btn" data-id4="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="name" contenteditable></td>
<td id="category" contenteditable></td>
<td id="cost" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test_db");
$sql = "INSERT INTO tbl_sample(name, category, cost) VALUES('".$_POST["name"]."', '".$_POST["category"]."', '".$_POST["cost"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Data Inserted';
}
?>
edit.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ecc");
$id = $_POST["id"];
$text = $_POST["text"];
$column_name = $_POST["column_name"];
$sql = "UPDATE task SET ".$column_name."='".$text."' WHERE id='".$id."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Updated';
}
?>
delete.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ecc");
$sql = "DELETE FROM task WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Deleted';
}
?>
you can use data tables for this, no need of all this
https://editor.datatables.net/examples/inline-editing/simple
check this, data tables provide libraries for this

Issue of undefined index while using ajax and php

I have four different files
index.php
select.php
insert.php
edit.php
delete.php
In my backend I have created a database named 'ecc'
Database 'ecc' has atable named 'task'
The table task has following fields
id, name, category, cost
Datatype for id set to int and index as primary also id field is on auto increment
My issue :( ! ) Notice: Undefined index: id in C:\wamp\www\select.php on line 38
and same for lines 39, 40, 41,
each of the error is displayed twice on the page.
index.php
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Live Table Add Edit Delete using Ajax Jquery in PHP Mysql</h3><br />
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
var name = $('#name').text();
var category = $('#category').text();
if(name == '')
{
alert("Enter service Name");
return false;
}
if(category == '')
{
alert("Enter category");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{name:name, category:category},
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
function edit_data(id, text, column_name)
{
$.ajax({
url:"edit.php",
method:"POST",
data:{id:id, text:text, column_name:column_name},
dataType:"text",
success:function(data){
alert(data);
}
});
}
$(document).on('blur', '.name', function(){
var id = $(this).data("id1");
var name = $(this).text();
edit_data(id, name, "name");
});
$(document).on('blur', '.category', function(){
var id = $(this).data("id2");
var category = $(this).text();
edit_data(id,category, "category");
});
$(document).on('click', '.btn_delete', function(){
var id=$(this).data("id3");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
</script>
select.php
<?php
$connect = mysqli_connect('localhost', 'root', '','ecc');
mysqli_select_db($connect,'ecc');
if(!$connect){
echo "yes";
}else{
echo "no";
}
$output = '';
$sql = "SELECT name, category FROM addservices ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">Service Name</th>
<th width="40%">Category</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="name" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
<td class="category" data-id2="'.$row["id"].'" contenteditable>'.$row["category"].'</td>
<td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="name" contenteditable></td>
<td id="category" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
You are getting this error Undefined index: id
Because you have not put id in select query
$sql = "SELECT id,name, category FROM addservices ORDER BY id DESC";
Chek your query.It need to change as:
$sql = "SELECT * FROM task ORDER BY id DESC";
You are getting this error because you have not selected "id" field in the $sql statement.
You have writen -
$sql = "SELECT name, category FROM addservices ORDER BY id DESC";
It should be
$sql = "SELECT id, name, category FROM addservices ORDER BY id DESC";

How do I add (sum of numbers) within a data-table in ajax even if a new row is added with jquery

I'm trying to make an addition (or subtraction if needed) to a php page with ajax.
What this code is supposed to do is add all the prices up and give me the correct sum with the live-edit-table.
if a user changes the value of price $price_total should change acordingly.
Even if a new row is added it should still give the new sum (displayed in $price_total and $final_price_total) with the new row included.
I have been trying to figure out how to do this but I can't figure out how.
$price_total and $final_price_total do not get saved into a database
this is the code that I have so far:
index.php
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data(){
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
while (str.length <= n) {
str = "0" + str;
}
var pt = str.length - n;
return str.slice(0,pt) + "." + str.slice(pt);
}
fetch_data();
function edit_data(id, text, column_name){
$.ajax({
url:"edit.php",
method:"POST",
data:{
id:id,
text:text,
column_name:column_name
},
dataType:"text",
success:function(data){
/*alert(data);*/
}
});
}
$(document).on('click', '#btn_add', function(){
/* this function would also add the prices to the table*/
var price = $('#price').text();
var final_price = $('#final_price').text();
if(price == ''){
alert("Enter Price");
return false;
}
if(final_price == ''){
alert("Enter Final Price");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{price:price, final_price:final_price},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
})
});
$(document).on('blur', '.price', function(){
var id = $(this).data("id1");
var price = $(this).text();
edit_data(id, price, "price");
/*I'm trying so that I can add the new input price with the old total to give the exact value*/
$total = parseFloat( price ) + parseFloat( $('#price_total').value );
$('#price_total').value = formatDecimal(total);
});
$(document).on('blur', '.final_price', function(){
var id = $(this).data("id2");
var final_price = $(this).text();
edit_data(id, final_price, "final_price");
});
});
select.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test_db");
$output = '';
$sql = "SELECT * FROM tbl_sample ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">Price</th>
<th width="40%">Final Price</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0){
$final_price_total = 0;
$price_total = 0;
while($row = mysqli_fetch_array($result)){
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="price" data-id1="'.$row["id"].'" contenteditable>'.$row["price"].'</td>
<td class="final_price" data-id2="'.$row["id"].'" contenteditable>'.$row["final_price"].'</td>
<td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
$final_price_total += $row["final_price"];
$price_total += $row["price"];
}
$output .= '
<tr>
<td></td>
<td class="price_total" id="price_total" name="price_total" value="'.$price_total.'" contenteditable>'.$price_total.'</td>
<td class="final_price_total" id="final_price_total" name="final_price_total" value="'.$final_price_total.'" contenteditable>'.$final_price_total.'</td>
<td></td>
</tr>
';
$output .= '
<tr>
<td></td>
<td id="price" contenteditable></td>
<td id="final_price" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else{
$output .= '<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
From the little discussion in the question comments, I've managed to spot this variable typo:
$total = parseFloat( price ) + parseFloat( $('#price_total').value );
$('#price_total').value = formatDecimal(total);
On the second line you are using total instead of $total.
If you check your browser's error console, you will see an error about undeclared variable total.
Edit: after further discussion, you wanted to know how to loop over the table in JavaScript and add up the total. Try this:
var newTotal = 0.0;
$('.price').each(function() {
newTotal += parseFloat($(this).text());
});
If you do this on your edit finding, you can then use the newTotal variable in the final_price field in place of where you are using the $total variable.

Categories