datatable plugin php and json errror - php

i am new to programming.i try to design a admin panel that can directly edit the users data with the help of datatable plugin.this there is some error with JSON format
this is my index page
<html>
<head>
<title>Live Add Edit Delete Datatables Records using PHP Ajax</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<style>
body
{
margin:0;
padding:0;
background-color:#f1f1f1;
}
.box
{
width:1270px;
padding:20px;
background-color:#fff;
border:1px solid #ccc;
border-radius:5px;
margin-top:25px;
box-sizing:border-box;
}
</style>
</head>
<body>
<div class="container box">
<h1 align="center">Live Add Edit Delete Datatables Records using PHP Ajax</h1>
<br />
<div class="table-responsive">
<br />
<div align="right">
<button type="button" name="add" id="add" class="btn btn-info">Add</button>
</div>
<br />
<div id="alert_message"></div>
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Staff id</th>
<th>Password</th>
<th>Email_id</th>
<th>gender</th>
<th>qualification</th>
<th>course1</th>
<th>course2</th>
<th>course3</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
fetch_data();
function fetch_data()
{
var dataTable = $('#user_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"fetch.php",
type:"POST"
}
});
}
function update_data(id, column_name, value)
{
$.ajax({
url:"update.php",
method:"POST",
data:{id:id, column_name:column_name, value:value},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
$(document).on('blur', '.update', function(){
var id = $(this).data("id");
var column_name = $(this).data("column");
var value = $(this).text();
update_data(id, column_name, value);
});
$('#add').click(function(){
var html = '<tr>';
html += '<td contenteditable id="data1"></td>';
html += '<td contenteditable id="data2"></td>';
html += '<td contenteditable id="data3"></td>';
html += '<td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs">Insert</button></td>';
html += '</tr>';
$('#user_data tbody').prepend(html);
});
$(document).on('click', '#insert', function(){
var first_name = $('#data1').text();
var last_name = $('#data2').text();
var password = $('#data3').text();
if(first_name != '' && last_name != '' && password != '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:{first_name:first_name, last_name:last_name, password:password},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
else
{
alert("Both Fields is required");
}
});
$(document).on('click', '.delete', function(){
var id = $(this).attr("id");
if(confirm("Are you sure you want to remove this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
success:function(data){
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
});
});
</script>
This is my fetch.php file
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "flash");
$columns = array('staff_id', 'password','email_id','gender','qualification','course1','course2','course3');
$query = "SELECT * FROM staff ";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE staff_id LIKE "%'.$_POST["search"]["value"].'%"
OR email_id LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'
';
}
else
{
$query .= 'ORDER BY id DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="staff_id">' . $row["staff_id"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="password">' . $row["password"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="email_id">' . $row["email_id"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="gender">' . $row["gender"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="qualification">' . $row["qualification"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="course1">' . $row["course1"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="course2">' . $row["course2"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="course3">' . $row["course3"] . '</div>';
$sub_array[] = '<button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row["SINO"].'">Delete</button>';
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM staff";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
?>
this shows an alert message like
DataTables warning: table id=user_data - Invalid JSON response. For
more information about this error, please see
http://datatables.net/tn/1
the fetch.php file shows a error statement like
Notice: Undefined index: length in C:\xampp\htdocs\FLASH\admin
modify\fetch.php on line 28
Notice: Undefined index: start in C:\xampp\htdocs\FLASH\admin
modify\fetch.php on line 30
Notice: Undefined index: length in C:\xampp\htdocs\FLASH\admin
modify\fetch.php on line 30
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result,
boolean given in C:\xampp\htdocs\FLASH\admin modify\fetch.php on line
33
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
boolean given in C:\xampp\htdocs\FLASH\admin modify\fetch.php on line
39
Notice: Undefined index: draw in C:\xampp\htdocs\FLASH\admin
modify\fetch.php on line 62
{"draw":0,"recordsTotal":4,"recordsFiltered":null,"data":[]}
guy please help me to solve this issue please.

Related

How to load an editable table with AJAX

My site uses AJAX to load menus without having to refresh the page. For future reference, the main php file that contains all the menus is the index.php file. One of these menus has an editable table, which uses AJAX, jQuery and Datatable plugin. All the menus seem to load correctly, but the table doesn't load upon the first click, and then after it does load, it acts wrong; I try to add a single record, but it adds a random number of the record instead (for example, like 16 records). Also, for some reason, the appearance of the table changes; it's normal if the script source (the script being the Datatable script) is a cdn link, however it's messed up a bit if the source is a file (even though the file has the same code, except for the names of buttons and etc shown being in Hungarian, instead of English). None of the listed problems happen if the table's menu is loaded normally, without AJAX, but loading it with AJAX just messes it up, and I have no clue why.
Table after the first click on the Autok button
This is how the table looks by default
Table after adding only one record
As you can see, even though I added just one record (the one with test1), it got inserted 6 times... also, everything on the site just doubled; double search bars, buttons, etc... before I added the test1 record, there really were only 9 entries, so it appears, the 9 entries text remained from before the record was added, and above that the new, 15 entries text was loaded. So, my question is: how do I make it, so that only that one records I actually inserted gets inserted (and not with a random number of copies)? Also, how do I get rid of the double search bars and such after insertion, and how do I make it, so that the table properly displays even after the first click on the Autok button on the left?
I tried using a newer jQuery and Database sourcecode, but it didn't do anything. I also tried to remove the $(document).ready(function()... parts of the code, either only from the index.php file, or from the autok.php file, but neither worked. As I mentioned before, if the table's menu is loaded without AJAX, everything works like a charm (the table itself still operates with AJAX), but I need it to load with AJAX, so I want to fix this. As for the database (MySQL), everything refreshes and works as it should, though for some reason I can't seem to delete the records that were wrongly inserted multiple times, because even if I click on delete (within phpmyadmin, it just... stays there.
This makes the table's menu (autok, which gets its content from autok.php) load without refreshing any pages, by clicking on its button (button's ID is autok), and then loading the table in a large div (which has the cell-content ID).
This is the code responsible for loading the Autok menu, it's found in my index.php file (just ignore the "belépés" and "regisztráció" parts, those work differently, not with AJAX):
<div id="menuk" class='belso bal'>
<?php
if(empty($_SESSION["username"]))
{
echo"<a href='?p=belep' >Belépés</a>";
}
else
{
echo"<a href='autok.php' id='autok'>Autók</a>";
echo"<a href='alkalmazottak.php' id='alkalmazottak'>Alkalmazottak</a>";
echo"<a href='vevok.php' id='vevok' >Vevők</a>";
}
echo"<a href='?p=reg'>Regisztráció</a>";
?>
</div>
<div id="cell-content" class='belso jobb' >
<script>
$(document).ready(function(){
$("#autok").click(function(){
$("#cell-content").load('autok.php');
return false;
});
});
$(document).ready(function(){
$("#alkalmazottak").click(function(){
$("#cell-content").load('alkalmazottak.php');
return false;
});
});
$(document).ready(function(){
$("#vevok").click(function(){
$("#cell-content").load('vevok.php');
return false;
});
});
</script>
This is the Autok menu's php (autok.php):
<html>
<head>
<title>Autószalon</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<style>
#user_data {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#user_data td, #user_data th {
border: 1px solid #ddd;
padding: 8px;
}
#user_data tr:nth-child(even){background-color: #f2f2f2;}
#user_data tr:hover {background-color: #ddd;}
#user_data th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<h1 align="center">Autószalon</h1>
<br />
<div class="table-responsive">
<br />
<div align="right">
<button type="button" name="add" id="add" class="btn btn-info">Hozzáad</button>
</div>
<br />
<div id="alert_message"></div>
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Autó</th>
<th>Ár</th>
<th>Alkalmazott</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
fetch_data();
function fetch_data()
{
var dataTable = $('#user_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"fetch.php",
type:"POST"
}
});
}
function update_data(id, column_name, value)
{
$.ajax({
url:"update.php",
method:"POST",
data:{id:id, column_name:column_name, value:value},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
$(document).on('blur', '.update', function(){
var id = $(this).data("id");
var column_name = $(this).data("column");
var value = $(this).text();
update_data(id, column_name, value);
});
$('#add').click(function(){
var html = '<tr>';
html += '<td contenteditable id="data1"></td>';
html += '<td contenteditable id="data2"></td>'
html += '<td contenteditable id="data3"></td>';
html += '<td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs">Beszúrás</button></td>';
html += '</tr>';
$('#user_data tbody').prepend(html);
});
$(document).on('click', '#insert', function(){
var auto = $('#data1').text();
var ar = $('#data2').text();
var alkalmazott = $('#data3').text();
if(auto != '' && ar != '' && alkalmazott !='')
{
$.ajax({
url:"insert.php",
method:"POST",
data:{auto:auto, ar:ar, alkalmazott:alkalmazott},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
else
{
alert("Egy mezot kihagyott!");
}
});
$(document).on('click', '.delete', function(){
var id = $(this).attr("id");
if(confirm("Biztosan torolni szeretne?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
success:function(data){
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
});
});
</script>
As for the referenced PHPs, here is my fetch.php code:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "autoszalon");
if (!mysqli_connect_errno() && mysqli_set_charset($connect, "utf8"))
{
$columns = array('ID', 'Auto', 'Ar', 'Alkalmazott');
$query = "SELECT * FROM automenu ";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE auto LIKE "%'.$_POST["search"]["value"].'%"
OR alkalmazott LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'
';
}
else
{
$query .= 'ORDER BY id DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["id"].'" data-column="Auto">' . $row["Auto"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["id"].'" data-column="Ar">' . $row["Ar"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["id"].'" data-column="Alkalmazott">' . $row["Alkalmazott"] . '</div>';
$sub_array[] = '<button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row["id"].'">Törlés</button>';
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM automenu";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
}
?>
Here is the update.php:
<?php
$connect = mysqli_connect("localhost", "root", "", "autoszalon");
if (!mysqli_connect_errno() && mysqli_set_charset($connect, "utf8"))
{
if(isset($_POST["id"]))
{
$value = mysqli_real_escape_string($connect, $_POST["value"]);
$query = "UPDATE automenu SET ".$_POST["column_name"]."='".$value."' WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $query))
{
echo 'Adat Frissitve';
}
}
}
?>
Here is the insert.php:
<?php
$connect = mysqli_connect("localhost", "root", "", "autoszalon");
if (!mysqli_connect_errno() && mysqli_set_charset($connect, "utf8"))
{
if(isset($_POST["auto"], $_POST["ar"], $_POST["alkalmazott"]))
{
$auto = mysqli_real_escape_string($connect, $_POST["auto"]);
$ar = mysqli_real_escape_string($connect, $_POST["ar"]);
$alkalmazott = mysqli_real_escape_string($connect, $_POST["alkalmazott"]);
$query = "INSERT INTO automenu(auto, ar, alkalmazott) VALUES('$auto', '$ar', '$alkalmazott')";
if(mysqli_query($connect, $query))
{
echo 'Adat Elmentve';
}
}
}
?>
And here is the delete.php code:
<?php
$connect = mysqli_connect("localhost", "root", "", "autoszalon");
if(isset($_POST["id"]))
{
$query = "DELETE FROM automenu WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $query))
{
echo 'Adat Torolve';
}
}
?>

codeigniter ajax cart update quantity

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

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