Ajax does not take all params - javascript

I have a litte problem with the update. I have a couple of forms (over a loop). The script works fine with the first form, but with the others there is a problem.
while ($zeile = mysqli_fetch_array( $result, MYSQL_ASSOC))
{
....
$_SESSION['date'][$a] = $zeile['submit_time'];
$_SESSION['bes'][$a] = $zeile['date'];
<form id="upload" method="post" name="form">
<td>
<input onclick="this.value='';" class="datepicker" type="text" name="date" value="<?php echo $date_bes; ?>"/ readonly></td>
<script>
$(function() {
$( ".datepicker" ).datepicker();
});
</script>
<td style='text-align:center;width:120px;'>
<input id="chk<?php echo $a; ?>" class="chk" name="chk" type="checkbox" value=""
<?php if($check == 1){ echo "checked"; }else{ echo "";} ?>/>
<input type="hidden" class="id" value="<?php echo $id_submit; ?>">
</td>
<td style="text-align:center;width:240px;">
<textarea id="remark<?php echo $a; ?>" class="remark" name="remark" cols="30" rows="1" ><?php echo $remark; ?></textarea>
</td>
<td>
<input class="submit" type="image" src="save.jpg"></td>
</form>
...
}
my ajax_script.js
$(document).ready(function() {
$( "#upload" ).on("submit", function(e) {
e.preventDefault();
var id = $('.id').val();
var date = $('.datepicker').val();
var chk = $('.chk').prop('checked');
var remark = $('.remark').val();
$.ajax({
type: 'POST',
url: 'update.php',
data: {id: id, date: date, chk: chk, remark: remark},
success: function (data) {
if(data.success == true)
{
console.log('everything fine');
}
},
error: function(){
console.log('something bad happened');
}
});
alert('Job done');
});
});
and the update.php
<?php
$id = $_POST['id'];
$date = $_POST['date'];
$chk = $_POST['chk'];
$cancel_bool = ((int)$chk) ? 1 : 0;
$remark = $_POST['remark'];
$year = substr($date,6,4);
$mon = substr($date,3,2);
$day = substr($date,0,2);
$date = $year.'-'.$mon.'-'.$day;
if($chk == "true"){
$chk = 1;
}else{
$chk = 0;
}
echo "<br>";
echo $id ."<br>".$date."<br>".$chk."<br>".$remark;
require_once('config.php');
$link = mysqli_connect (
MYSQL_HOST,
MYSQL_USER,
MYSQL_PASSWORD,
MYSQL_DATABASE
);
if(!$link){
die('connection failed: ' .mysql_error());
}
$sql = "UPDATE table1
SET date = '$date', cancel_bool ='$chk', remark = '$remark' WHERE id_submits = $id";
$result = mysqli_query( $link, $sql );
?>
With the first form it posts the following param by clicking on save.jpg:
chk true
date 16.04.2014
id 1396002713.9412
remark mytext_one
second form:
chk
date 08.04.2014
remark mytext_two
Where is the id?
Any help or idea?
Greets Yab86

Related

Filter date from data base with ajax and jquery with the help of form?

I have four file in php first one is feedback that contain data table where I try to display my data feedback.php are below
<?php
error_reporting(E_ALL);
ini_set('display_error',1);
include_once('header.php');
//include_once('sidemenu.php');
require_once('Class_Library/class_Feedback.php');
?>
<?php
$obj = new Feedback();
//$clientid = $_SESSION['clientId'];
$feedbackdata = $obj->GetAllFeedback();
if($feedbackdata['success']==1)
{
$data=$feedbackdata['data'];
//print_r($data);
}
else {
$data=[];
}
//print_r($fedbackdata);
//die;
?>
<style>
.dataTables_filter {
float: right;
}
.pagination{
float: right;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="js/home_page.js"></script>
<script>
$(document).ready(function () {
var startdate = document.getElementById("feedbackstartdate").value;
var enddate = document.getElementById("feedbackenddate").value;
var site = document.getElementById("site").value;
// alert("end "+enddate);
// alert("start "+startdate);
$feedbackdata=showfeedbacklist(startdate, enddate,site);
});
</script>
<script>
function feedbackindex()
{
//alert("hello, your code is here");
var startdate= document.getElementById("fromDate").value;
var enddate= document.getElementById("toDate").value;
var site= document.getElementById("site").value;
//alert('start '+startdate);
//alert('enddate '+enddate);
if (startdate == "")
{
window.alert("Please select From date.");
document.getElementById("fromDate").focus();
return false;
}
if (enddate == "")
{
window.alert("Please select To date.");
document.getElementById("toDate").focus();
return false;
}
if (startdate > enddate )
{
window.alert("From date can't be greater then To date.");
document.getElementById("toDate").focus();
return false;
}
$feedbackdata = showfeedbacklist(startdate, enddate,site);
/**************************************************************************/
}
</script>
<!--page content -->
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default" style="margin-top: 25px;">
<div class="panel-heading">
<h4>Feedback</h4>
</div>
<form id="formdata" method="post">
<div class="col-md-4">
<div class="form-group">
<label for="pwd">From: </label>
<input type="date" id="fromDate" name="FSDate" size="20" class="form-control input" placeholder="mm/dd/yyyy"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="pwd">To: </label>
<input type="date" id="toDate" class="form-control" name="FSDate" size="20" placeholder="mm/dd/yyyy"/>
</div>
</div>
<div class="col-md-4" style="margin-top:20px;">
<div class="form-group">
<input type="hidden" name="feedbackstartdate" id="feedbackstartdate" value="<?php echo date('Y-m-d', strtotime("-7 days")); ?>">
<input type="hidden" id="feedbackenddate" name="feedbackenddate" value="<?php echo date('Y-m-d', strtotime("-1 days")); ?>">
<input type="" id="site" name="site" value="<?php echo SITE; ?>"
<center><button type="button" class="btn btn-info" onclick="return feedbackindex();">Submit</button></center>
</div>
</div>
</form>
<div class="panel-body">
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example"> <thead>
<tr>
<th>Cutomer Name</th>
<th>Location</th>
<th>Visit Type</th>
<th>Visit By</th>
<th>Visit Dtae</th>
<th>Feedback</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < count($data); $i++) {
?>
<tr>
<td><?php echo $data[$i]['CustomerName'];?></td>
<td><?php echo $data[$i]['clientCity']; ?></td>
<td><?php echo $data[$i]['TaskType']; ?></td>
<td><?php echo $data[$i]['visitByName']; ?></td>
<td><?php echo $data[$i]['visitDate'];?></td>
<td><?php
$datafeedback = $data[$i]['feedbackValue'];
if($datafeedback==null)
{
echo 'pending';
}
else{
if($datafeedback==5)
{
echo '<img src="images/feedback/greenSmile.png" alt="send feedback by data"style="width:50px;height:50px;" />';
}
elseif ($datafeedback==4) {
echo '<img src="images/feedback/smile.png" alt="send feedback by data"style="width:50px;height:50px;" />';
}
elseif ($datafeedback==3) {
echo '<img src="images/feedback/redsmile.png" alt="send feedback by data"style="width:50px;height:50px;" />';
}
}
?></td>
<td>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!--/page content -->
<?php include 'footer.php'; ?>
My code is proper work when we try to display to data but when we try to filter I don't know how to work that and my link file of js are
function showfeedbacklist(startdate, enddate, site)
{
var postData =
{
"startdate":startdate ,
"enddate": enddate,
"site" :site
};
var dataString = JSON.stringify(postData);
// alert(dataString);
$.ajax({
type: "post",
// dataType: "json",
//contentType: "application/json; charset=utf-8",
url:site+"Link_Library/link_getfeedbacklist.php",
data: {"mydata": dataString},
success: function (response) {
var respdata = response;
// alert(respdata);
console.log(respdata);
},
error: function (e) {
alert(e);
console.log(e.message);
}
});
}
and my ajax page where i am send to data are
<?php
require_once('../Class_Library/class_Feedback.php');
$obj = new Feedback();
if (!empty($_POST["mydata"])) {
$jsonArr = $_POST["mydata"];
// echo $jsonArr;
$data = json_decode($jsonArr, true);
//print_r($data);
//die;
if (!empty($data)) {
$fromdt1 = $data['startdate'];
$fromdt = date("Y-m-d H:i:s", strtotime($fromdt1));
// echo "statrt date-".$fromdt;
$enddte1 = $data['enddate'];
$enddte2 = date("Y-m-d", strtotime($enddte1));
$date123 = date_create($enddte2 ." 23:59:59", timezone_open("Asia/Kolkata"));
$enddate = date_format($date123, "Y-m-d H:i:s");
// echo "endd date-".$enddt;
$result = $obj->graphGetFeedbacklist($enddate, $fromdt);
// echo "<pre>";
// print_r($res);
}
}
?>
And my sql class file are last one that is
<?php
if (!class_exists('Connection_Communication')) {
include_once('class_connect_db_Communication.php');
}
class Feedback {
public $DB;
public function __construct() {
$db = new Connection_Communication();
$this->DB = $db->getConnection_Communication();
}
function GetAllFeedback() {
try {
$query = "select site.*,list.Service_Type,list.Id,(select Task_Type from tbl_task_type where Auto_Id = list.Service_Type) as TaskType,DATE_FORMAT(start_date,'%d-%b-%Y') as visitDate,CONCAT(usr.First_Name,' ',usr.Last_Name) as visitByName,(select SUM(parameter_value)/(select count(parameterId) from tbl_visit_feedback_parameter where parameterId < (select MAX(parameterId) from tbl_visit_feedback_parameter)) from tbl_visit_feedback_data where parameter_id < (select MAX(parameterId) from tbl_visit_feedback_parameter) and task_id = site.task_id) as feedbackValue from tbl_site_visit_detail as site JOIN tbl_master_user as usr ON site.employee_id = usr.ID JOIN tbl_tasks_list as list ON site.task_id = list.Task_Id where visit_status = '1'";
$stmt = $this->DB->prepare($query);
// $stmt->bindParam(':sd', $startdate, PDO::PARAM_STR);
// $stmt->bindParam(':ed', $enddate, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($row) {
require_once 'class_master.php';
$masObj = new Master();
$farray = array();
for ($i = 0; $i < count($row); $i++) {
$refid = $row[$i]['Id'];
$Service_Type = $row[$i]['Service_Type'];
$result = $masObj->getTaskDetail($refid, $Service_Type);
if ($result['success'] == 1) {
$data = $result['data'];
$temp = $data + $row[$i];
array_push($farray, $temp);
}
}
if (!empty($farray)) {
$response['success'] = 1;
$response['data'] = $farray;
} else {
$response['success'] = 0;
$response['message'] = 'No data found.';
}
} else {
$response['success'] = 0;
$response['data'] = 'error while fetching data ';
}
} catch (Exception $ex) {
$response['success'] = 0;
$response['data'] = $ex->getMessage();
}
return $response;
}
}
?>
I am new in codding area so i don't know how to handle that type problem and I sow so many references but I have no idea what happen there.

How do I filter for similar products using checkboxes with PHP, AJAX and JS?

Here is an image of what I'm trying to accomplish -
Example of my Database Table -
My goal is to get a similar product to the product that is currently displaying without refreshing the page. I am trying to find similar products is by using check boxes.
I first got the id using $_GET['id'] which should be equal to one of the values in my table.
I then used PDO Fetch to get the product name, brand, quanity and price of that particular id and store it as a string.
What I need help with is using JQuery/AJAX to get the checkboxes that are checked and then send the information to a PHP file that would check if filter results match with any data from the table.
How can I do this?
This is my product.php file
<?php
require ('includes/db.php');
$id = $_GET['id']; //Getting the ID in URL. ex products.php?id=12
$stmt = $handler->prepare("SELECT * FROM products WHERE id = '$id' ");
$result = $stmt->execute(array());
$products = $stmt->fetch(PDO::FETCH_ASSOC);
$prod_name = $products['prod_name']; //Product Name
$brand = $products['brand']; //Product Brand
$quantity = $products['quantity']; //Product Quantity
$calories = $products['calories']; //Product Calories
$price = $products['price']; //Product Price
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo "$brand $prod_name"; ?></title>
</head>
<body>
<h1><?php echo $prod_name; ?></h1>
<br />
<p>Brand = <?php echo " $brand"; ?></p>
<p>Quantity = <?php echo " $quantity"; ?></p>
<p>Calories = <?php echo " $calories"; ?></p>
<p>Price = <?php echo " $price"; ?></p>
<br />
<p style="text-align: center;">Find Similar Products</p>
<form>
<div class="checkboxes">
<label>
<input name="brand" type="checkbox" value="<?php echo $brand; ?>">
<span>Brand</span> <!--Brand Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="quanitity" type="checkbox" value="<?php echo $quantity; ?>">
<span>Quantity</span> <!--Quantity Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="calories" type="checkbox" value="<?php echo $calories; ?>">
<span>Calories</span> <!--Calories Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="price" type="checkbox" value="<?php echo $price; ?>">
<span>Price</span> <!--Price Checkbox-->
</label>
</div>
</form>
</body>
</html>
I managed to solve this out, glad I didn't give up.
My product.php File
<?php
require ('/db.php');
$id = $_GET['id']; //Getting the ID in URL. ex products.php?id=12
$stmt = $handler->prepare("SELECT * FROM products WHERE id = '$id' ");
$result = $stmt->execute(array());
$products = $stmt->fetch(PDO::FETCH_ASSOC);
$prod_name = $products['prod_name']; //Product Name
$brand = $products['brand']; //Product Brand
$quantity = $products['quantity']; //Product Quantity
$calories = $products['calories']; //Product Calories
$price = $products['price']; //Product Price
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo "$brand $prod_name"; ?></title>
</head>
<body>
<h1><?php echo $prod_name; ?></h1>
<br />
<p>Brand = <?php echo " $brand"; ?></p>
<p>Quantity = <?php echo " $quantity"; ?></p>
<p>Calories = <?php echo " $calories"; ?></p>
<p>Price = <?php echo " $price"; ?></p>
<br />
<p style="text-align: center;">Find Similar Products</p>
<form method="post" action="">
<div class="checkboxes">
<label>
<input name="brand" type="checkbox" value="<?php echo $brand; ?>">
<span>Brand</span> <!--Brand Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="quanitity" type="checkbox" value="<?php echo $quantity; ?>">
<span>Quantity</span> <!--Quantity Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="calories" type="checkbox" value="<?php echo $calories; ?>">
<span>Calories</span> <!--Calories Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="price" type="checkbox" value="<?php echo $price; ?>">
<span>Price</span> <!--Price Checkbox-->
</label>
</div>
</form>
<div class="filter_container">
<div style="clear:both;"></div>
</div>
<script type="text/javascript" src="/js/filter.js"></script>
<input name="prod_name" value="<?php echo $prod_name ?>" style="display:none;"/>
<!--Hidden product name-->
</body>
</html>
Here is my JS File
$(document).ready(function() {
function showValues() {
var brand;
var quantity;
var calories;
var price;
//Gets product name
var prod_name = $('input[name="prod_name"]').val();
//Gets brand
if($('input[name="brand"]').is(':checked'))
{brand = $('input[name="brand"]').val();} else {brand = ""}
//Gets quantity
if($('input[name="quantity"]').is(':checked'))
{quantity = $('input[name="quantity"]').val();} else {quantity = ""}
//Gets calories
if($('input[name="calories"]').is(':checked'))
{calories = $('input[name="calories"]').val();} else {calories = ""}
//Gets price
if($('input[name="price"]').is(':checked'))
{price = $('input[name="price"]').val();} else {price = ""}
$.ajax({
type: "POST",
url: "/query.php",
data: {'brand':brand, 'quantity':quantity, 'calories':calories, 'prod_name':prod_name},
cache: false,
success: function(data){
$('.filter_container').html(data)
}
});
}
//Call function when checkbox is clicked
$("input[type='checkbox']").on( "click", showValues );
//Remove checked when checkbox is checked
$(".checkboxes").click(function(){
$(this).removeAttr('checked');
showValues();
});
});
Here is my PHP File
<?php
include('/db.php');
$prod_name = $_POST['prod_name'];
$Cbrand = $_POST['brand'];
$Cquantity = $_POST['quantity'];
$Ccalories = $_POST['calories'];
$Cprice = $_POST['price'];
if(!empty($Cbrand))
{
$data1 = "brand = '$Cbrand' AND";
}else{
$data1 = "";
}
if(!empty($Cquantity))
{
$data2 = "quantity = '$Cquantity' AND";
}else{
$data2 = "";
}
if(!empty($Ccalories))
{
$data3 = "calories = '$Ccalories' AND";
}else{
$data3 = "";
}
if(!empty($Cprice))
{
$data4 = "price = '$Cprice'";
}else{
$data4 = "";
}
$main_string = "WHERE $data1 $data2 $data3 $data4"; //All details
$stringAnd = "AND"; //And
$main_string = trim($main_string); //Remove whitespaces from the beginning and end of the main string
$endAnd = substr($main_string, -3); //Gets the AND at the end
if($stringAnd == $endAnd)
{
$main_string = substr($main_string, 0, -3);
}else if($main_string == "WHERE"){
$main_string = "";
}
else{
$main_string = "WHERE $data1 $data2 $data3 $data4";
}
if($main_string == ""){ //Doesn't show all the products
}else{
$sql = "SELECT COUNT(*) FROM products $main_string";
if ($res = $handler->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
$sql = "SELECT * FROM products $main_string";
foreach ($handler->query($sql) as $pro) {
if(($pro['prod_name'] == $prod_name) && ($res->fetchColumn() < 2))
{
//The product currently being displayed is blank when using the filter
}
else{
?>
<!------------------------------------------------------------------------------------------------------------------------------------------------->
<div class="form-result">
<td><?=strtoupper($pro['brand']) + " " + strtoupper($pro['prod_name']); ?></td>
</div>
<!------------------------------------------------------------------------------------------------------------------------------------------------->
<?php
}
}
} /* No rows matched -- do something else */
else {
?>
<div align="center"><h2 style="font-family:'Arial Black', Gadget, sans-serif;font-size:30px;color:#0099FF;">No Results with this filter</h2></div>
<?php
}
}
}
$handler = null;
$res = null;
?>

noty jQuery - notification apearence

I want to show notification on delete all button. I use noty jquery while I click on delete all button only button of notification show not full and page redirected I am using codeigniter what I do the code below like as
// view of my file
<?php $page_url = $this->uri->segment(2);?>
<div id="contents" style="width:1024px;">
<div class="buttons">
<div><button class="button-choose-2 pure-button" id="delete">Delete</button></div>
<div>
<input type="button" class="button-choose-2 pure-button" name="CheckAll" value="Check All" onClick="checkAll(document.myform.list)"></div>
<div>
<input type="button" class="button-choose-2 pure-button" name="UnCheckAll" value="Uncheck All" onClick="uncheckAll(document.myform.list)"></div>
<div><button class="button-choose-2 pure-button">Add</button></div>
</div>
<br style="clear:both;">
<?php $this->load->view("includes/left_menu") ?>
<form name="myform" id="myform">
<div class="right-contents">
<table width="98%" cellpadding="5">
<tr class="right-top">
<td width="8%"> </td>
<td width="21%">Name</td>
<td width="18%">Image</td>
<td width="38%">Designation</td>
<td colspan="3" align="center">Actions</td>
</tr>
<?php if(is_array($items)): ?>
<?php foreach($items as $row){?>
<tr>
<td width="8%"><input type="checkbox" id="list" name="del[]" value="<?php echo $row->team_id;?>" class="del"></td>
<td width="21%"><?php echo $row->name?></td>
<td width="18%"><img src="assets/icons/<?php echo $row->photo?>" width="100" height="70"></td>
<td width="38%"><?php echo $row->designation?></td>
<td width="5%"><img src="assets/img/edit.png"></td>
<td width="5%"><img src="assets/img/27935.png"></td>
<td width="5%"><a href="parexons_con/delete/<?php echo
$row->team_id;?>/<?php echo $page_url ?>/<?php echo 'team'; ?>/<?php echo 'team_id'; ?>"><img src="assets/img/Delete-icon.png"></a></td>
</tr>
<?php } endif; ?>
</table>
</div>
</form>
<script>
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
</script>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#delete").on('click', function(e) {
var r = confirm("are you sure you want to delete this");
if (r==true) {
e.preventDefault();
var ids = $('.del:checked').map(function () {
return this.value;
}).get();
console.log(ids);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>parexons_con/delete_all",
data: 'id=' + ids,
type: "POST",
success: function (result) {
noty({text: 'thank you for providing information', type: 'success',settimeout:5000});
setTimeout(window.location.reload(), 1200000);
}
});
}
});
});
</script>
and controller are
function delete_all($del_id = NULL, $view = NULL, $table = NULL, $field_name = NULL)
{
$error = 'error';
$msg = 'deleted';
$ids = $this->input->post('id');
$explode = explode(",", $ids);
foreach ($explode as $id) {
$query = $this->parexons_model->delete_row('team', array('team_id' => $id));
}
if ($query) {
http_response_code(redirect("my_controller/team"), 5000);
} else {
redirect("my_controller/team");
}
}
Wrong syntax of jquery ajax data it would be
data: {id: ids},
Second do not redirect of controller function you need to pass some value to ajax success like
function delete_all($del_id = NULL, $view = NULL, $table = NULL, $field_name = NULL) {
$error = 'error';
$msg = 'deleted';
$ids = $this->input->post('id');
$explode = explode(",", $ids);
foreach ($explode as $id) {
$query = $this->parexons_model->delete_row('team', array('team_id' => $id));
}
if ($query) {
echo "success";
} else {
echo "false";
}
}

javascript innerhtml returning one result

When I click the checkbox, only the first row shows the text box.
Expected When I check the checkbox, the text box will show in that row.
When i click the submit button, it only inserts the data from the first row.
Example When I checked 3 boxes, it will insert the data from the first row 3 times.
How can I fix my code?
<script type="text/javascript">
function changeText(codeasset){
if(codeasset.checked){
document.getElementById('hotStuff').innerHTML = '<input type="text" id="hotStuff" style="width: 150px;" />';
}else {
document.getElementById('hotStuff').innerHTML='';
}}
</script>
<?php
$assets_supplier_query = mysql_query("SELECT * FROM supplier_assets WHERE status = '0' AND supplier_id = '$supplier_id'");
while ($get_supplier_asset = mysql_fetch_array($assets_supplier_query))
{
$asset_code = $get_supplier_asset['asset_code'];
$asset_qty = $get_supplier_asset['supply_quantity'];
$asset_query = mysql_query("SELECT * FROM ref_assetmodel WHERE modelID = '$asset_code' ");
$get_asset = mysql_fetch_array($asset_query);
$asset_model = $get_asset['assetModel'];
$specifications = $get_asset['specifications'];
$category_id = $get_asset['categoryID'];
$type_id = $get_asset['typeID'];
$category_query = mysql_query("SELECT * FROM ref_assetcategory WHERE categoryID = '$category_id' ORDER BY categoryID");
$get_category = mysql_fetch_array($category_query);
$category = $get_category['assetCategory'];
$type_query = mysql_query("SELECT * FROM ref_assettype WHERE typeID = '$type_id' ");
$get_type = mysql_fetch_array($type_query);
$type = $get_type['assetType'];
?>
<form action="../process/approve_supplies_process.php" method="post" name="supplier">
<td><input type="checkbox" id="codeasset" name="supply[]" onclick="changeText(this)" value="<?php echo $asset_code ?>"> </td>
<td name="supply[]"><?php echo $type; ?></td>
<td name="supply[]"><?php echo $asset_model; ?></td>
<td name="supply[]"><?php echo $asset_qty; ?></td>
<td name="supply[]" id="hotStuff" value="<?php echo $asset_code ?>"></td>
<?php
}
?>
<tr>
<td align="center"><input type="submit" class="edit_butt" name="action" value="Submit" onclick=""></td>
<input type="hidden" name="supplier_id" value="<?php echo $supplier_id; ?>">
</tr>
</form>
<?php
$asset_code = $_POST['asset_code'];
$categoryID = $_POST['category_id'];
$type_id = $_POST['type_id'];
$supplier_id = $_POST['supplier_id'];
date_default_timezone_set('Asia/Manila');
$inventoryDate= date("Y-m-d");
if(isset($_POST['supply'])){
foreach ($_POST['supply'] as $_value)
{
echo "Box #{$_value} was selected!\n";
mysql_query("INSERT INTO ref_inventory(inventoryDate, categoryID, typeID, modelID, serialNumber, qrCode, is_owned, supplier_id)
VALUES('$inventoryDate', '$categoryID', '$type_id', '$asset_code', '954', '', 1, '$supplier_id') ");
}
}
?>

update multiple checkbox with javascript and ajax

I am working with multiple checkboxes with javascript and ajax. When the checkbox is clicked the javascript send with ajax the values to trata.php (these values: checked if is true or false and the id of that checkbox)...but the id always show me undefined....can you guide me, please.
Here is the JS:
$("div.feature").click(function() {
var checked = $(this).is(':checked');
var Id = $(this).attr('id');
var data = "Cara=" + checked + "&Id=" + Id;
$.ajax({
type: "POST",
url: "trata.php?ts=" + new Date().getTime(),
data: data,
cache: false,
beforeSend: function() {
$("#tr").show();
$("#t").empty();
},
success: function(response) {
$("#tr").hide();
$("#t").append(response);
}
})
return false;
});
$("div.feature1").click(function() {
var checked = $(this).is(':checked');
var Id = $(this).attr('id');
var data = "Pieza=" + checked + "&Id=" + Id;
$.ajax({
type: "POST",
url: "trata.php?ts=" + new Date().getTime(),
data: data,
cache: false,
beforeSend: function() {
$("#tr").show();
$("#t").empty();
},
success: function(response) {
$("#tr").hide();
$("#t").append(response);
}
})
return false;
});
In page this is the code:
<table>
<tr>
<td>
<div class="feature" align="center">
<input type="text" value="<?php echo $row['Id'] ?>" name="Id" id="Id" /> <!-- in this Id the value is 1 -->
<input type="checkbox" data-no-uniform="true" class="iphone-toggle" <?php if ($row[ 'Cara']=='1' ) {echo 'name="Cara" value="on" checked="checked"';} else { echo 'name="Cara" value="off"'; } ?>>
</div>
<div id="tr" style="display:none;" align="center"><img src="img/ajax-loaders/ajax-loader-1.gif" />
</div>
<div id="t"></div>
</td>
<td>
<div class="feature1" align="center">
<input type="text" value="<?php echo $row['Id']; ?>" name="Id" id="Id" /> <!-- in this Id the value is 2 -->
<input type="checkbox" data-no-uniform="true" class="iphone-toggle" <?php if ($row[ 'Pieza']=='1' ) {echo 'name="Pieza" value="on" checked="checked"';} else { echo 'name="Pieza" value="off"'; } ?>>
</div>
<div id="tr" style="display:none;" align="center"><img src="img/ajax-loaders/ajax-loader-1.gif" />
</div>
<div id="t"></div>
</td>
</tr>
</table>
In trata.php //MySQL + PDO
<?php
include('conn.php');
if(isset($_POST['Cara'])) {
try{
$Id = $_POST['Id'];
if ($_POST['Cara'] == false) {
global $Cara;
$Cara = 0;
} else if ($_POST['Cara'] == true) {
global $Cara;
$Cara = 1;
};
$sql = "UPDATE Trata SET
Cara = :Cara
WHERE Id= :Id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':Cara', $Cara, PDO::PARAM_STR);
$stmt->bindParam(':Id', $Id, PDO::PARAM_INT);
$stmt->execute();
echo "<div class='alert alert-block alert-primary fade in'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
ok.
</div>";
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
} if(isset($_POST['Pieza'])) {
try{
$Id = $_POST['Id'];
if ($_POST['Pieza'] == false) {
global $Pieza;
$Pieza = 0;
} else if ($_POST['Pieza'] == true) {
global $Pieza;
$Pieza = 1;
};
$sql = "UPDATE Trata SET
Pieza = :Pieza
WHERE Id= :Id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':Pieza', $Pieza, PDO::PARAM_STR);
$stmt->bindParam(':Id', $Id, PDO::PARAM_INT);
$stmt->execute();
echo "<div class='alert alert-block alert-primary fade in'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
ok.
</div>";
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
}
$dbh = null;
?>
Another thing is the loading ajax is show me only in the first td and I have 8 td files..
div.feature and div.feature1 do not have ids. That is why $(this).attr('id') is returning undefined. Try this:
$('div.feature input:checkbox').click(function(){
var Id = $(this).attr('id');
});

Categories

Resources