update multiple checkbox with javascript and ajax - javascript

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

Related

AJAX JSON loaded form buttons refreshes page instead on working with AJAX again

I have a strange problem here. I am processing data via AJAX from a table loaded inside while loop and when the data is successfully processed the table gets reloaded with new data via AJAX and JSON. The problem is that when the new table is loaded and I click the same submit button from any row again then this time instead of processing it via AJAX it works as a normal submit button and refreshes the page. Then when the page is refreshed the submit button works via AJAX again. Why is it not working with AJAX when the table was reloaded via AJAX after previous operation via AJAX when in both the tables the parameters used are exactly the same? My codes are below. Please tell my what's wrong here and what's the solution for this.
membership.php
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Memberships List</h3>
</div>
<div class="card-body table-responsive p-0">
<table class="table table-hover table-striped" id="mbslist">
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php
$i = 1;
$mem = $pdo->prepare("SELECT * FROM memberships");
$mem-> execute();
while($m = $mem->fetch()){ extract($m);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
?>
<tr>
<td><?php echo $i; ?></td>
<td><span style="color: <?php echo $mem_color; ?>"><?php echo $mem_name; ?></span></td>
<td>₹<?php echo $mem_daily_capping; ?></td>
<td>₹<?php echo $mem_earn_amount; ?></td>
<td>₹<?php echo $mem_min_payout; ?></td>
<td><?php echo $mem_payout_percent; ?>%</td>
<td><?php if($mem_price == '0.00'){ echo "Free"; }else{ echo "₹$mem_price"; } ?></td>
<td><span class="<?php echo $statusColor; ?>"><?php echo ucfirst($mem_status); ?></span></td>
<td>
<form method="post" action="">
<input type="hidden" value="<?php echo $mem_id; ?>" class="memid">
<input type="hidden" value="<?php echo $status; ?>" class="status">
<input type="hidden" value="memstatus" class="type">
<?php if($mem_id != 1){ ?>
<input type="submit" class="btn <?php echo $btn; ?> mbslist" value="<?php echo ucfirst($btnVal); ?>">
<?php } ?>
Edit
</form>
</td>
</tr>
<?php $i++; } ?>
</table>
</div>
</div>
</div>
<div class="message"></div>
</div>
AJAX Code
// Set Membership Status
$(document).ready(function(){
$(".mbslist").click(function() {
var dataString = {
id: $(this).closest('tr').find('.memid').val(),
type: $(this).closest('tr').find('.type').val(),
status: $(this).closest('tr').find('.status').val()
};
console.log(dataString);
$.ajax({
type: "POST",
dataType : "json",
url: "processes/memberships.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$('.overlay').fadeIn();
},
success: function(json){
$('.message').html(json.status);
setTimeout(function(){
$('.overlay').fadeOut();
$('.message').fadeIn();
$('#mbslist').html(json.table).fadeIn();
}, 2000);
}
});
return false;
});
});
processes/memberships.php
<?php
include('../../config/db.php'); include('../../functions.php');
$memid = (!empty($_POST['id']))?$_POST['id']:null;
$type = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;
$color = (!empty($_POST['color']))?$_POST['color']:null;
$name = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price = (!empty($_POST['price']))?$_POST['price']:null;
if($_POST){
if($type == 'memstatus'){
$update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
$update-> bindValue(':status', $status);
$update-> bindValue(':id', $memid);
$update-> execute();
if($update){
$pro = $pdo->prepare("SELECT * FROM memberships");
$pro-> execute();
$table = "<table class='table table-hover table-striped' id='mbslist'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>";
$i = 1;
while($p = $pro->fetch()){ extract($p);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
$table .= "<tr>
<td>".$i."</td>
<td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
<td>₹".$mem_daily_capping."</td>
<td>₹".$mem_earn_amount."</td>
<td>₹".$mem_min_payout."</td>
<td>".$mem_payout_percent."%</td>
<td>".$mp."</td>
<td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
<td>
<form method='post' action=''>
<input type='hidden' value=".$mem_id." class='memid'>
<input type='hidden' value=".$status." class='status'>
<input type='hidden' value='memstatus' class='type'>
<input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
<a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
</form>
</td>
</tr>";
$i++;
}
$table .= "</table>";
echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
}else{
echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
}
}
}
Modify your processes/memberships.php with following code:
$memid = (!empty($_POST['id']))?$_POST['id']:null;
$type = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;
$color = (!empty($_POST['color']))?$_POST['color']:null;
$name = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price = (!empty($_POST['price']))?$_POST['price']:null;
if($_POST){
if($type == 'memstatus'){
$update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
$update-> bindValue(':status', $status);
$update-> bindValue(':id', $memid);
$update-> execute();
if($update){
$pro = $pdo->prepare("SELECT * FROM memberships");
$pro-> execute();
$table = "<table class='table table-hover table-striped' id='mbslist'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>";
$i = 1;
while($p = $pro->fetch()){ extract($p);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
$table .= "<tr>
<td>".$i."</td>
<td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
<td>₹".$mem_daily_capping."</td>
<td>₹".$mem_earn_amount."</td>
<td>₹".$mem_min_payout."</td>
<td>".$mem_payout_percent."%</td>
<td>".$mp."</td>
<td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
<td>
<form method='post' action=''>
<input type='hidden' value=".$mem_id." class='memid'>
<input type='hidden' value=".$status." class='status'>
<input type='hidden' value='memstatus' class='type'>
<input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
<a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
</form>
</td>
</tr>";
$i++;
}
$table .= "</table>";
echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
}else{
echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
}
}
}
?>
<script>
// Set Membership Status
$(document).ready(function(){
$(".mbslist").click(function() {
var dataString = {
id: $(this).closest('tr').find('.memid').val(),
type: $(this).closest('tr').find('.type').val(),
status: $(this).closest('tr').find('.status').val()
};
console.log(dataString);
$.ajax({
type: "POST",
dataType : "json",
url: "processes/memberships.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$('.overlay').fadeIn();
},
success: function(json){
$('.message').html(json.status);
setTimeout(function(){
$('.overlay').fadeOut();
$('.message').fadeIn();
$('#mbslist').html(json.table).fadeIn();
}, 2000);
}
});
return false;
});
});
</script>
Hope this might help you.
Your submit button will try to submit form normally when you click it. So just use "event.preventDefault() " as below so your button wont trigger normal form submission and now wont load the page.
$(".mbslist").click(function(event) {
event.preventDefault();
}

ajax delete post asynchronously - php

I'm trying to create a add/delete/edit post system using php for a website. I have the add working, so when the user enters in information it gets added to the database and then asynchronously gets added onto the page using ajax. I want a similar function that deletes asynchronously as well. Right now, when I click delete, only the oldest post gets deleted AFTER refreshing the page. It does not delete the post as soon as I click the delete button which is my goal. This is what I have so far. The home.php is where my form is that collects the information and also prints out the information from the database. handledelete.php is where the deleting is handled.
home.php
<script>
$(function() {
$('#deleteButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#show_entries").append(html);
}
});
});
});
</script>
<div id="entry">
<form method="GET" action="handle_insert.php">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="activity" id="activity" placeholder="Activity" required /></td>
</tr>
<tr>
<td><input type="text" name="duration" id="duration" placeholder="Duration (hours)" required /></td>
</tr>
<tr>
<td><input type="text" name="date" id="date_" placeholder="Date (YYYY-MM-DD)" required /></td>
</tr>
<tr>
<td><button type="submit" name="submitButton" id="submitButton">Add input</button></td>
</tr>
</table>
</form>
</div>
<!-- shows the previous entries and adds on new entries-->
<div id="show_entries">
<?php
$userID = $_SESSION["user"];
$link = mysqli_connect('localhost', 'oviya', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '<button type="submit" name="deleteButton" data-id='.$entry_id.' id= "deleteButton">Delete</button>';
//echo '<button type="submit" name="editButton" data-id='.$entry_id.' id="editButton">Edit</button>';
echo '</div>';
}
?>
</div>
handle_delete.php
session_start();
$user = 'oviya';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_GET["entry_id"])){
$entry_id = mysqli_real_escape_string($link, $_GET["entry_id"]);
$sql = "DELETE FROM dataTable WHERE entry_id = '$entry_id'";
$result = mysqli_query($link, $sql);
die();
mysqli_close($link);
}
This line is the problem. It would add elements if your AJAX call were returning HTML, which it isn't:
$("#show_entries").append(html);
Instead, you want to remove the deleted element, which you can reference directly and remove from the DOM:
$('#deleteButton').click(function(event) {
event.preventDefault();
// Get a reference to the whole row element.
var row = $(this).parent();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
success: function(html){
// Remove the row
row.remove();
}
});
});

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

save multi checkbox by id

I am working with live checkbox, so when I need to put ON(1) or OFF(0) one checkbox immediately the checkbox update the value in the DB and all is ok...but now I am working with live checkbox in a user list(which I already have right now 100 users)...so the problem is when I try to put someone a ban, the checkbox just only works with the last one and not in the others users... can you please help me?
Here is the form:
<form class="form-horizontal" method="post" name="ban" id="ban">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<?php if ($row['banned'] == '1') {
echo '<input type="checkbox" name="banned" data-no-uniform="true" class="iphone-toggle" value="on" checked>';
} else {
echo '<input type="checkbox" name="banned" data-no-uniform="true" class="iphone-toggle" value="off" >';
} ?>
</form>
<div id="gif" style="display:none;" align="center"><img src="img/ajax-loaders/ajax-loader-1.gif" /></div>
Here the JS:
$("#ban").click(function(){
$.ajax({
type:"POST",
url:"includes/ban.php?ts=" + new Date().getTime(),
dataType:"text",
data:$(this).serialize(),
beforeSend:function(){
$("#gif").show();
},
success:function(response){
$("#gif").hide();
}
})
return false;
});
And this is the code to DB:
<?php
include('con.php');
if($_POST['banned']==on) {
try{
$id = $_POST['id'];
$banned = '0';
$sql = "UPDATE BANS SET
banned = :banned
WHERE id= :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':banned', $banned, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
echo "<div class='alert alert-block alert-success fade in'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
the ban is off!.
</div>";
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
} else {
try{
$id = $_POST['id'];
$banned = '1';
$sql = "UPDATE BANS SET
banned = :banned
WHERE id= :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':banned', $banned, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
echo "<div class='alert alert-block alert-danger fade in'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
the ban is on!
</div>";
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
}
$dbh = null;
?>
The reason only the last one is getting submitted is because you can't assign the same id to multiple elements.
Change: <form class="form-horizontal" method="post" name="ban" id="ban">
To: <form class="form-horizontal ban" method="post">
Then update your jQuery selector to $("form.ban")
Finally, in your PHP: if($_POST['banned']==on) {
Should be: if($_POST['banned']=='on') {
Edit: As a side-note, the same problem will affect the AJAX loader GIF, assuming again that you have an AJAX loader in each row, but that's outside the scope of this question.

Ajax does not take all params

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

Categories

Resources