Instant Checkbox update on sql rows with ajax and jquery - php

Example of what I want:
Hi i want on each row to update instant the checkbox with value 1 when checked and 0 when not checked.
I've make some steps and already taken in a URL via post the values, but I see that updates only on the first row of my table. I think it must have some foreach or loop on ajax to take value to other rows?
This value will export as a URL querystring (ischeck) to an extrnal URL to take import on my function to make the sql query to update the value.
Here is the javascript that for sure want changes about loop that I haven't put on charges.php.
<script>
$(function($) {
var arr = [];
$('input.checkbox').on('change', function() {
var id = "<?php echo $charge['id'] ?>";
var check_active = $(this).is(':checked') ? 1 : 0;
var check_id = $('[id^="checked-]');
arr.push(check_active);
var url = "ajax_ischeck.php?id=" + id + "&ischeked=" + check_active;
console.log("url", url);
if (this.checked) {
$.ajax({
url: url,
type: "GET",
dataType: 'html',
success: function(response) {
},
});
}
});
});
</script>
Here is the table with the input checkbox sry its little big the checkbox is down to last lines on Charges.php:
<tbody>
<?php foreach ($showcharge as $charge) { ?>
<tr>
<td><?php echo htmlspecialchars($charge['created_at']); ?></td>
<td><?php echo htmlspecialchars($charge['tasks']); ?> </td>
<th width="5%"><?php if (empty($charge['taskcharges'])) {
echo "Free";
} else {
echo htmlspecialchars($charge['taskcharges'] . "\xE2\x82\xAc");
} ?></th>
<th width="5%"><?php
if (empty($charge['payment'])) {
echo htmlspecialchars($charge['payment']);
} else {
echo htmlspecialchars($charge['payment'] . "\xE2\x82\xAc");
}
?>
</th>
<th width="5%" id="balance"><?= htmlspecialchars($charge['balance'] . "\xE2\x82\xAc") ?></th>
<th width="10%"><?php if (($charge['payment_date'] == 0000 - 00 - 00)) {
echo "";
} else {
echo htmlspecialchars($charge['payment_date']);
} ?></th>
<th width="10%"><?php echo htmlspecialchars($charge['admin']); ?></th>
<th width="15%"><?php echo htmlspecialchars($charge['comments']); ?></th>
<td class="mytd">
<form action="" method="POST">
<a href="editcharge.php?id=<?php echo $charge['id'];
echo '&custid=' . $customer['id'] ?>" class="btn btn-info " role=" button " aria-disabled=" true">Edit</a>
</form>
<form id="delete-<?php echo $charge['id'] ?>" onSubmit="return confirm('Are you sure you want to delete?')" method="post">
<input type="hidden" name="id_to_delete" value="<?php echo $charge['id'] ?>" />
<input type="submit" class="btn btn-danger" name=" delete" value="delete" />
</form>
<script>
$("#delete").submit(function() {
return confirm("Are you sure you want to delete?");
});
</script>
</td>
<th width="7%"> <input class="checkbox" type="checkbox" checked value="1" id="checked-1" name="checbox"> <label> Success </label> </input> </th>
</tr>
<?php } ?>
</tbody>
The ajax_ischeck.php that gets data from charges.php post :
<?php include('dataprocess.php'); ?>
<?php include('config/pdo_connect.php'); ?>
<?php
$id = $_GET['id'];
$ischeck = $_GET['ischeck'];
if(isset($_GET["ischeck"])){
Data::ischecked($id, $ischeck);
}
and the sql query:
public static function ischecked ($id, $ischeck)
{
$sql = "UPDATE charges SET
ischecked='$ischeck'
WHERE id=$id";
$statement = conn()->prepare($sql);
$statement->execute();
/* echo $sql;
die(); */
if (!$statement) {
echo "\nPDO::errorInfo():\n";
}
}

Related

Ajax confirmation is asking only for one data

I have implemented an ajax beforeSend function where there is a confirm(), the problem is that in the code if I want to delete the first value in while it asks for confirm but if I click the second or third or fourth, it just goes to the URL in the method and executes the command
this is the the page
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<?php
$stmt = $DB_con->prepare("SELECT * FROM people");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{?>
<tr><td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<form method="post" id="del" action="delete.php">
<input type='hidden' id='pid' name='pid' value='<?php echo $row['id']; ?>'>
<button id="send" type="submit">Delete</button>
</form>
</th>
</tr>
<?php
}
?>
this is the ajax function
$(document).ready(function (e) {
$("#del").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "delete.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend:function(){
return confirm("Are you sure you want to delete this?");
},
success: function(data)
{
alert("Delete Successful");
window.location.reload();
},
error: function(e)
{
}
});
}));
});
whereas it should ask no matter which record I want to delete, it should ask for confirmation.
use classname class="del" instead of id id="del".Each time submit its only execute first form
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<?php
$stmt = $DB_con->prepare("SELECT * FROM people");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{?>
<tr><td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<form method="post" class="del" action="delete.php">
<input type='hidden' class='pid' name='pid' value='<?php echo $row['id']; ?>'>
<button id="send" type="submit">Delete</button>
</form>
</th>
</tr>
<?php
}
?>
Here you create invalid HTML:
while(...)
{
...
'>
Delete
...
}
In every loop-run you create 3 objects with identical id in each run. An ID must not defined multiple times.
Solutions:
Don't use id=and use optional class=.
Append an unique number to id, e.g. id="del-<?php echo $row['id']; ?>"

How to get values from foreach loop of php in jquery

I'm Working on a plugin in Wordpress in which i'm storing values in new table which is created on plugin activation its working perfectly.
Now I fetched values from table like following
<tbody>
<?php
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_ajc_images");
foreach ($result as $row) {
?>
<tr id="list_item">
<td width="12%">
<img src="<?php echo $row->ajc_img_path ?>" width="100">
</td>
<td width="22%">
<input type="text" class="img_link" value="<?php $row->ajc_img_link ?>" size="30">
<input type="hidden" class="ajc_field_id" value="<?php echo $row->ajc_img_id ?>">
</td>
<td width="26%">
<textarea rows="3" class="img_description"><?php $row->ajc_img_description ?></textarea>
</td>
<td width="22%">
<input type="text" class="img_title" value="<?php $row->ajc_img_title ?>" size="30">
</td>
<td width="20%">
<input type="submit" id="update" value="Update">
<button class="delete">Delete</button>
</td>
</tr>
<?php
}
?>
</tbody>
after fetching the data I display the values in form of listing.
Now I want to update values of input fields and textarea through ajax for which I wrote following code
add_action('wp_ajax_ajc_update_values', 'ajc_update_value');
add_action('wp_ajax_nopriv_ajc_update_values', 'ajc_update_value');
add_action("admin_head", "ajc_input_ajax");
function ajc_input_ajax()
{
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#update").click(function () {
var id = jQuery('.ajc_field_id').val();
var update_link = jQuery('.img_link').val();
var update_desc = jQuery('.img_description').val();
var update_title = jQuery('.img_title').val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
});
</script>
<?php
}
//Updating values in database
function ajc_update_value()
{
$id = $_POST['ajc_id'];
$link = $_POST['ajc_update_link'];
$desc = $_POST['ajc_update_desc'];
$title = $_POST['ajc_update_title'];
global $wpdb;
$wpdb->update(
'wp_ajc_images',
array(
'ajc_img_title' => $title,
'ajc_img_description' => $desc,
'ajc_img_link' => $link
),
array('ajc_img_id' => $id)
)
die();
return true;
}
When I click on first item's update button it alerts me right id eg. (12) and update it, but when I click on rest of the item's update button it alerts me first item's id (12) and data is not updated.
Hope you'll understand my question.
Try this code. add id to every fields like id="img_link_<?php echo $row->ajc_img_id; ?>"
HTML code
<tbody>
<?php
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_ajc_images");
foreach ($result as $row) {
?>
<tr id="list_item">
<td width="12%">
<img src="<?php echo $row->ajc_img_path ?>" width="100">
</td>
<td width="22%">
<input type="text" id="img_link_<?php echo $row->ajc_img_id; ?>" class="img_link" value="<?php $row->ajc_img_link ?>" size="30">
<input type="hidden" class="ajc_field_id" value="<?php echo $row->ajc_img_id; ?>">
</td>
<td width="26%">
<textarea rows="3" id="img_description_<?php echo $row->ajc_img_id; ?>" class="img_description"><?php $row->ajc_img_description ?></textarea>
</td>
<td width="22%">
<input type="text" id="img_title_<?php echo $row->ajc_img_id; ?>" class="img_title" value="<?php $row->ajc_img_title ?>" size="30">
</td>
<td width="20%">
<input type="submit" data-id="<?php echo $row->ajc_img_id; ?>" id="update" value="Update">
<button class="delete">Delete</button>
</td>
</tr>
<?php
}
?>
</tbody>
Script code
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#update").click(function () {
var id =jQuery(this).attr('data-id');
var update_link = jQuery('#img_link'+id).val();
var update_desc = jQuery('#img_description'+id).val();
var update_title = jQuery('#img_title'+id).val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
});
</script>
You're displaying values based on a class name and there could be many elements with same class name. What you need to do is target specific <tr> and get values from that <tr> only.
So your jQuery code should look like this:
jQuery("#update").click(function () {
var id = $(this).parents('tr').find('.ajc_field_id').val();
var update_link = $(this).parents('tr').find('.img_link').val();
var update_desc = $(this).parents('tr').find('.img_description').val();
var update_title = $(this).parents('tr').find('.img_title').val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
You just have to add $(this).parents('tr').find before selecting values from every element.

how to update the php variable using jquery variable

Hi I am developing a shopping cart.The products ordered by a customer is shown to him. All the products and their details are stored in a session variable. He can change the quantity of each product, if he wants to.When he changes the quantity of a product,corresponding price changes.This I have done using jquery. Now I need to update the session variable,when he changes the quantity. And I have to display it also.
Here is my code.
<?php
session_start();
include('head.php');
?>
<!DOCTYPE HTML>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
GrandTotal();
});
GrandTotal();
});
function GrandTotal(){
var GrandTotal=0;
var cart=0;
$(".myclass").each(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
cart +=parseInt(Qty);
var Total = Qty * Price;
GrandTotal += Total;
$("#priceDisplay_"+identifier).html(Total);
});
$("#cart").html(cart);
$("#GrandTotal").html(GrandTotal);
}
function RemoveCart(ob){
if (confirm("Are you sure to Remove?"))
{
var IdForRemove =ob.value;
$.ajax({
type: "POST",
url: "RemoveCart.php",
dataType:'json',
data: { id: IdForRemove}
})
.done(function( data ) {
$("#GrandTotal").html(data.Grandtotal);
$("#cart").html(data.cart);
$("#"+IdForRemove).remove();
});
return false;
}
}
</script>
</head>
<body>
<?php
if(empty($_SESSION['items'])){ ?>
<center><b><font color="red">There are no products in your cart!!</font></b></center>
<?php
}
else
{
?>
<b><font color="#0000A0"> Your Shopping Cart!!</font></b><br><br>
<form name="formview" action="orderform.php" method="post">
<?php $count=0;
?>
<table id="mytable" width="50%" cellpadding="1px" cellspacing="3px" border="1" bgcolor="#BDEDFF">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Remove</th>
</tr>
<?php
$cnt=0;
$CartR = $_SESSION['r'];
foreach( $CartR as $key=>$ar):
$Identifier = 'qty_'.$cnt;
?> <tr id="<?php echo $ar['Id']; ?>">
<td align="center"><?php echo $ar['Name']?></td>
<td align="center"><?php echo $ar['Price']?></td>
<td align="center">
<select class="myclass" name="qty" id='<?php echo $Identifier;?>' >
<?php for ($i=1; $i<=100; $i++) {
$y="";
if( $i==$_SESSION['r'][$key]['Quantity']){
$y="selected";
}
echo "<option ";
echo "value=\"$i\" ".$y.">", $i, "</option>\n";
} ?>
</select>
</td>
<?php $x=$x+$ar['Quantity']; ?>
<td name="price"><span id="priceDisplay_<?php echo $Identifier;?>"><?php echo $ar['Total']; ?></span></td>
<input type='hidden' name='id' id="pid_<?php echo $Identifier;?>" value='<?php echo $ar['Id']; ?>'>
<input type='hidden' name='price' id="price_<?php echo $Identifier;?>" value='<?php echo $ar['Price'] ?>' class="input">
<td>
<input type="checkbox" onclick="RemoveCart(this)" value="<?php echo $ar['Id']; ?>">
<?php $tt[]=$ar['Total']; ?>
</tr>
<?php
$cnt++;
endforeach;
?> </table>
<br><br>
<table>
<tr></tr>
<tr><b><font color="B048B5">Grand Total :</font></b> <span id="GrandTotal"></span></tr>
<b><!--<font color="#F6358A">Your Cart:--></font></b><div align="center" id="cart"></div>
<center> <img src="upload/images.jpeg" width="100"></center>
</table>
<!--<table align="right">-->
<?php foreach($tt as $t)
{
$count=$count+$t;
}
?>
<br>
<br>
<!--<b><div id="cart">Your Cart:</div></b> -->
<?php
}
if(!empty($_SESSION['r']))
{ ?>
<input type="submit" name="checkout" value="CheckOut">
<?php } ?>
<b><font color="#7D0541">Back</font></b>
</form>
</body>
Anyone please help me. The change I made using jquery should also change my php variables.
This is my updated sessionupdate.php
<?php session_start();
include('head.php');
$qnty=$_GET['quantity'];
$prce=$_GET['price1'];
$_SESSION['r']=$_GET['id'];
$pid=$_GET['pid'];
foreach ($_SESSION['r'] as $key => $value) {
if($key==$pid){
$_SESSION['r'][$key]['Quantity']= $qnty;
$_SESSION['r'][$key]['Total']= $prce*$qnty;
}
}
here pid is my product_id passed from ajax.Please help me
If you want to update your php variable then you can do so via ajax.Try to do like this:
$(document).ready(function() {
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
GrandTotal();
//Call an ajax function here
$.ajax({
type: "GET",
url: "sessionupdate.php",
data: { quantity:Qty,price1:Price,id: <?php echo $_SESSION['r'];?>},
success:function(data){
alert(data);
}
});
});
GrandTotal();
});
sessionupdate.php:
<?php session_start();
include('head.php');
$qnty=$_GET['quantity'];
$prce=$_GET['price1'];
$_SESSION['r']=$_GET['id'];
$pid=$_GET['pid'];
foreach ($_SESSION['r'] as $key => $value) {
if($key==$pid){
$_SESSION['r'][$key]['Quantity']= $qnty;
$_SESSION['r'][$key]['Total']= $prce*$qnty;
echo $_SESSION['r'][$key]['Quantity'];
echo $_SESSION['r'][$key]['Total'];
}
}

Updating session variable based on changes made by jquery

Hi I am developing a shopping cart.The products ordered by a customer is shown to him. All the products and their details are stored in a session variable. He can change the quantity of each product, if he wants to.When he changes the quantity of a product,corresponding price changes.This I have done using jquery. Now I need to update the session variable,when he changes the quantity. And I have to display it also.
Here is my code.
<?php
session_start();
include('head.php');
?>
<!DOCTYPE HTML>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
GrandTotal();
});
GrandTotal();
});
function GrandTotal(){
var GrandTotal=0;
var cart=0;
$(".myclass").each(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
cart +=parseInt(Qty);
var Total = Qty * Price;
GrandTotal += Total;
$("#priceDisplay_"+identifier).html(Total);
});
$("#cart").html(cart);
$("#GrandTotal").html(GrandTotal);
}
function RemoveCart(ob){
if (confirm("Are you sure to Remove?"))
{
var IdForRemove =ob.value;
$.ajax({
type: "POST",
url: "RemoveCart.php",
dataType:'json',
data: { id: IdForRemove}
})
.done(function( data ) {
$("#GrandTotal").html(data.Grandtotal);
$("#cart").html(data.cart);
$("#"+IdForRemove).remove();
});
return false;
}
}
</script>
</head>
<body>
<?php
if(empty($_SESSION['items'])){ ?>
<center><b><font color="red">There are no products in your cart!!</font></b> </center>
<?php
}
else
{
?>
<b><font color="#0000A0"> Your Shopping Cart!!</font></b><br><br>
<form name="formview" action="orderform.php" method="post">
<?php $count=0;
?>
<table id="mytable" width="50%" cellpadding="1px" cellspacing="3px" border="1" bgcolor="#BDEDFF">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Remove</th>
</tr>
<?php
$cnt=0;
$CartR = $_SESSION['r'];
foreach( $CartR as $key=>$ar):
$Identifier = 'qty_'.$cnt;
?> <tr id="<?php echo $ar['Id']; ?>">
<td align="center"><?php echo $ar['Name']?></td>
<td align="center"><?php echo $ar['Price']?></td>
<td align="center">
<select class="myclass" name="qty" id='<?php echo $Identifier;?>' >
<?php for ($i=1; $i<=100; $i++) {
$y="";
if( $i==$_SESSION['r'][$key]['Quantity']){
$y="selected";
}
echo "<option ";
echo "value=\"$i\" ".$y.">", $i, "</option>\n";
} ?>
</select>
</td>
<?php $x=$x+$ar['Quantity']; ?>
<td name="price"><span id="priceDisplay_<?php echo $Identifier;?>"><?php echo $ar['Total']; ?></span></td>
<input type='hidden' name='id' id="pid_<?php echo $Identifier;?>" value='<?php echo $ar['Id']; ?>'>
<input type='hidden' name='price' id="price_<?php echo $Identifier;?>" value='<?php echo $ar['Price'] ?>' class="input">
<td>
<input type="checkbox" onclick="RemoveCart(this)" value="<?php echo $ar['Id']; ?>">
<?php $tt[]=$ar['Total']; ?>
</tr>
<?php
$cnt++;
endforeach;
?> </table>
<br><br>
<table>
<tr></tr>
<tr><b><font color="B048B5">Grand Total :</font></b> <span id="GrandTotal"></span></tr>
<b><!--<font color="#F6358A">Your Cart:--></font></b><div align="center" id="cart"></div>
<center> <img src="upload/images.jpeg" width="100"></center>
</table>
<!--<table align="right">-->
<?php foreach($tt as $t)
{
$count=$count+$t;
}
?>
<br>
<br>
<!--<b><div id="cart">Your Cart:</div></b> -->
<?php
}
if(!empty($_SESSION['r']))
{ ?>
<input type="submit" name="checkout" value="CheckOut">
<?php } ?>
<b><font color="#7D0541">Back</font></b>
</form>
</body>
The change I made using jquery should also change my php variables.
Can you try this.
Added UpdateCart function,
function UpdateCart(Qty, IDCart){
$.ajax({
type: "POST",
url: "UpdateCart.php",
dataType:'json',
data: {id:IDCart, Qty: Qty}
})
.done(function( data ) {
});
return false;
}
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
var IDCart = $("#pid_"+identifier).val();//passing reference value
UpdateCart(Qty, IDCart);//added this for update qty
GrandTotal();
});
GrandTotal();
});
Create one new file : UpdateCart.php
<?php session_start();
if(isset($_POST['id'])){
$toBeUpdate =$_POST['id'];
$CartR =$_SESSION['r'];
$Quantity = $_POST['Qty'];
foreach($CartR as $key=>$Cart){
if($Cart['Id']==$toBeUpdate){
$_SESSION['r'][$key]['Quantity']=$Quantity;
}
}
echo json_encode(array('success'=> true));
}
?>

Checkbox Data Dynamically Save to Database on Click

I need some js/ajax/jquery script saving data to database dynamically when I check the check-box.
the checkboxes at the moment or loaded in next to records and change the variable in the database depending if its checked or not.but i have to reload the page after i select one to save it to the database. i can do everything else but understand how to implement the ajax to this so i don't have to submit the query and refresh the page every time. any help is greatly appreciated.
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['first']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type=text name="comment" placeholder="Comments Box">
<input type=text name="cost" placeholder="Cost">
<input type="submit" value="Save" name="Save">
</form>
<?php
//Job Status
if(isset($_POST['checkbox'])){$checkbox = $_POST['checkbox'];
if(isset($_POST['activate'])?$activate = $_POST["activate"]:$deactivate = $_POST["deactivate"])
$id = "('" . implode( "','", $checkbox ) . "');" ;
$sql="UPDATE repairs SET status = '".(isset($activate)?'Completed':'In Progress')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Job Status
//Payment Status
if(isset($_POST['paycheck'])){$paycheck = $_POST['paycheck'];
if(isset($_POST['paid'])?$paid = $_POST["paid"]:$unpaid = $_POST["unpaid"])
$id = "('" . implode( "','", $paycheck ) . "');" ;
$sql="UPDATE repairs SET paid = '".(isset($paid)?'Paid':'Unpaid')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Payment Status
//Return Status
if(isset($_POST['retcheck'])){$retcheck = $_POST['retcheck'];
if(isset($_POST['ret'])?$ret = $_POST["ret"]:$unret = $_POST["unret"])
$id = "('" . implode( "','", $retcheck ) . "');" ;
$sql="UPDATE repairs SET ret = '".(isset($ret)?'Retuned':'In Office')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Return Status
$sql="SELECT * FROM $tbl_name";
if(isset($_POST['all'])){
$sql="SELECT * FROM $tbl_name";
}
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%'";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%'";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%'";
}
$result=mysql_query($sql);
?>
<form name="frmactive" method="post" action="">
<input name="activate" type="submit" id="activate" value="Complete Job" />
<input name="paid" type="submit" id="Payment" value="Payment Status" />
<input name="ret" type="submit" id="ret" value="Returned 2 Student" />
<br />
<a id="displayText" href="javascript:toggle();">Show Extra</a>
<div id="toggleText" style="display: none">
<br />
<input name="unret" type="submit" id="unret" value="In Office" />
<input name="unpaid" type="submit" id="unpaid" value="Not Paid" />
<input name="deactivate" type="submit" id="deactivate" value="In Progress" /></div>
<table width="1000" border="0" cellpadding="3" cellspacing="1">
<thead>
<th width="67" align="center"><strong>Start Date</strong></th>
<th width="50" align="center"><strong>Cases</strong></th>
<th width="34" align="center"><strong>Type</strong></th>
<th width="120" align="center"><strong>Damage</strong></th>
<th width="31" align="center"><strong>Comment</strong></th>
<th width="31" align="center"><strong>Cost</strong></th>
<th width="90" align="center"><strong>Payment Status</strong></th>
<th width="100" align="center"><strong>Returned 2 Student</strong></th>
<th width="100" align="center"><strong>Job Status</strong></th>
</thead>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['start']; ?></td>
<td><? echo $rows['cases']; ?></td>
<td><? echo $rows['type']; ?></td>
<td width="70"><? echo $rows['damage']; ?></td>
<td width="70"><? echo $rows['comment']; ?></td>
<td><? echo "$"; echo $rows['cost']; ?></td>
<!--Payment Display(Start)-->
<?php
if($rows['paid']=="Paid")
{
?>
<td><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid'];?>
</td>
<?
}
if($rows['paid']=="Unpaid")
{
?>
<td width="21"><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid']; ?>
</td>
<?
}
if($rows['ret']==""){
?>
<td width="50">No Data</td>
<?
}
?>
Do it with jQuery, a simple example could be:
HTML:
<input type="checkbox" name="option1" value="Milk">
<input type="checkbox" name="option2" value="Sugar">
<input type="checkbox" name="option3" value="Chocolate">
JS:
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('file.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
PHP: file.php
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
// error happened
print(0);
}
mysql_select_db('mydb');
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query
$sql = "INSERT INTO table (value) VALUES ('$value')";
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
?>
Simple put...
$('input:checkbox').click( function() {
clicked = $(this).attr('checked');
if (clicked) {
/* AJAX the server to tell them it was clicked. */ }
else {
/* AJAX the server to tell them it was unclicked. */ } } );
I can make this even simpler. first, you need to ad a checkbox!!
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['frist']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange="fill_damage(document.form1aa.type.selectedIndex);">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type="text" name="comment" placeholder="Comments Box">
<input type="text" name="cost" placeholder="Cost">
<input type="checkbox" name="somecheck" onchange="if(this.checked)document.form1aa.submit()">Check this to Save.
<input type="submit" value="Save" name="Save">
</form>
<script type="javascript>
//another function that works for onchange="dosubmit(this)"
//IF you put it after the form.
function dosubmit(el) {
if (el.checked) {
document.form1aa.submit();
}
}
</script>
get rid of the spaces in your onchange events where possible.
If you have dynamic checkbox list and you want to dynamically save the clicked one to database or inserting the unchecked one, here how to do that:
Html/PHP
<?php
// $checklists are models that I am getting from db
$checklists = CheckList::getCheckLists(3);
echo '<ul>';
foreach ($checklists as $checklist) {
$isChecked = $checklist->getAnswer($requestID, $checklist->primaryKey);
$checked = $isChecked ? "checked" : "";
echo '<li>';
echo "<input id='{$checklist->primaryKey}'
name='{$checklist->primaryKey}' type='checkbox' {$checked}
value='{$isChecked}' data-request-id='{$requestID}'>
$checklist->check_list_text";
echo '</li>';
}
echo '</ul>';
?>
Jquery
<script>
$("input[type='checkbox']").on('click', function(){
var checkbox = $(this);
var checked = checkbox.prop('checked');
var checklistId = checkbox.attr("id");
$.ajax({
url:"<?= Url::to(['default/add-checklist-answer']) ?>",
// I don't need to write the type here because I am using Yii Framework
// type: 'post',
data: {
checklistId: checklistId,
requestId: checkbox.data('request-id'),
checked: checked
},
success: function(data) {
//alert(data);
console.log(data.firstMessage)
},
error: function(data) {
// alert(data);
}
});
});
</script>
I hope it will work for MVC users.

Categories