Checkboxes inside a table with php foreach - php

I have a pretty much simple issue with a table i create with PHP foreach (in codeigniter).
One column inside the table has 2 checkboxes. One true and one false so when i create the table has some names and infos and then 2 checkboxes. Whenever the user clicks the true I create an AJAX POST call to my database to change the state of a column. But when the user has clicked true and then he clicks false I want the true checkbox to be unchecked.
Here is the code
<table class="responstable">
<tr>
<th>ID</th>
<th><span>Name</span></th>
<th>number1</th>
<th>number2</th>
</tr>
<?php
foreach($students as $column => $data ) { ?>
<tr>
<td><?php echo $data[0]->Userproperties_UserAM; ?></td>
<td><?php echo $data[0]->Userproperties_UserFullName; ?></td>
<td><?php echo $data[0]->UserAbsence; ?></td>
<td> <input class="true" id="<?php echo $data[0]->Userproperties_UserId; ?>" type='checkbox' value="<?php echo $data[0]->Userproperties_UserAM; ?>" />
<label for='true'>
<span></span>
True
</label>
<input class="false" id="<?php echo $data[0]->Userproperties_UserId; ?>" type='checkbox' value="<?php echo $data[0]->Userproperties_UserAM; ?>" />
<label for='false'>
<span></span>
False
</label></td>
</tr>
<?php } ?>
</table>
And the ajax code
$(document).ready(function() {
$('.true').change(function() {
if($(this).is(":checked")) {
$('.false').attr('checked', false);
var moduleid = <?php echo $moduleid; ?>;
var teacherid = <?php echo $teacherid; ?>;
var studentid = $(this).attr('id');
var weeknum = $("#dropi").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/TeacherParousies/send_parousia",
data: {
moduleid: moduleid,
studentid: studentid,
teacherid: teacherid,
parousia: 1,
weeknum: weeknum
},
success: function(res) {
},
error: function(err) {
}
});
}
});
$('.false').change(function() {
if($(this).is(":checked")) {
$('.true').attr('checked', false);
var moduleid = <?php echo $moduleid; ?>;
var teacherid = <?php echo $teacherid; ?>;
var studentid = $(this).attr('id');
var weeknum = $("#dropi").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/TeacherParousies/send_parousia",
data: {
moduleid: moduleid,
studentid: studentid,
teacherid: teacherid,
parousia: 0,
weeknum: weeknum
},
success: function(res) {
},
error: function(err) {
}
});
}
});
});
The problem here is that when i check the 2nd row of the table's checkbox lets say false, there is a change on the 1st row for true if it is checked.
Although I have stated
if($(this).is(":checked"))
Any idea?

In your case it .false and .true will uncheck all. You just need to check the nearest element.
Kindly replace the code $('.true').attr('checked', false); with this code $(this).closest( "td" ).find('.true').attr('checked', false);
and do same with for $('.false').attr('checked', false); this $(this).closest( "td" ).find('.false').attr('checked', false);

Related

How to delete multiple records using php and ajax

I have multiple rows of news when I show them using php. I'm trying to remove multiple rows simultaneously using checkboxes next to each row.
This is my php code
<?
$select_news = $mysqli->query("SELECT * FROM news order by time desc limit $x,$numbershownews");
while ($rows_news = $select_news->fetch_array(MYSQL_ASSOC)){
$id_news = $rows_news ['id'];
$title_news = $rows_news ['title'];
?>
<table>
<tr rel="<? echo $id_news; ?>">
<td class="tdtable" id="<? echo $id_news; ?>" width="4%">
<input type="checkbox" rel="<? echo $id_news; ?>" name="checkbox[]" class="checkboxtable" value="<? echo $id_news; ?>">
</td>
<td class="tdtable" id="<? echo $id_news; ?>" width="50%">
<? echo $title_news; ?>
</td>
</tr
</table
<?
}
?>
<button class="deletecheckednews">Delete</button>
and this is jquery code
$(".deletecheckednews").on( 'click', function () {
var arr = new Array();
$(".checkboxtable:checked").each(function () {
arr.push($(this).attr("rel"));
});
if(arr == "") {
alertify.error("no selected news");
} else {
$.ajax({
type: "POST",
url: "action/delete_multiple_news.php",
data: arr ,
cache: false,
success: function(data) {
alertify.success(data);
$.each(arr, function(key, value) {
$("tr[rel="+value+"]").fadeOut();
});
}
});
}
return false
});
How can I pass this array on to "delete_multiple_news.php"? I have tried this $checkedneww = $_REQUEST['arr']; and this $checkedneww = $_POST['arr']; but it doesn't work. How would I go about removing the selected rows?
On
$.ajax({
type: "POST",
url: "action/delete_multiple_news.php",
data: {"array_del": arr} , / <-
cache: false,
success: function(data){
alertify.success(data);
In PHP use
$array_del = filter_input(INPUT_POST, 'array_del', FILTER_SANITIZE_STRING);
If you wanna see the result, just do:
In PHP ajax:
$array_del = filter_input(INPUT_POST, 'array_del', FILTER_SANITIZE_STRING);
echo json_encode($array_del);
In js:
$.ajax({
type: "POST",
url: "action/delete_multiple_news.php",
data: arr ,
cache: false,
success: function(data){
alertify.success(data);
console.debug(data);
//$.each(arr, function(key, value) {
// $("tr[rel="+value+"]").fadeOut();
//});
}
});
To delete you can use WHERE in sql to filter the results who you want delete example. If the results are more than one, you make a loop or a commun column.
$mysqli->query(DELETE FROM table_name WHERE some_column = $array_del[some_column]);
You're passing a raw array in your ajax call (data: arr) but you're expecting a named variable ($_POST['arr']).
I'm not sure if data: arr is possible with jquery (haven't used it in years) but if it is, then the ids array you're looking for is simply $_POST in its whole.
If that's not the case, or you want to do $_POST['arr'] you should change your JS to data: {arr: arr}.

PHP with jquery datatables with CRUD just can edit visible record

I'm using jquery datatables but there's something problem.
I have total 11 records. Data tables show me 10 entries of record from database and I add column for edit and delete
But when I click pagination button , data tables show me 1 record (record number 11), but the button of edit and delete is not work
Can you help me ?
This my code
<?php
while($row_dosen = mysql_fetch_assoc($q_dosen)){
?>
<tr>
<td><?php echo $row_dosen['nik'];?></td>
<td><?php echo $row_dosen['nama']; ?></td>
<td align="center"><span class="label label-success2" style="font-size:14px;">
<?php echo $row_dosen['jurusan_nama']; ?><span><td>
<td align="center">
<?php echo $row_dosen['status_name']; ?>
</td>
<td align="center">
<?php echo $row_dosen['email']; ?>
</td>
<td align="center">
<?php echo $row_dosen['no_hp']; ?>
</td>
<td align="left">
<?php
//$pizza = mysql_query("SELECT dosen.skill_id, dosen.skill_name, skill.skill_id, skill.skill_name FROM dosen, skill WHERE dosen.skill_id = skill.skill_id ",$conn);
$pieces = explode(",", $row_dosen['skill_id']);
$j = 1;
for($i = 0; $i < count($pieces) ; $i++){
//echo ''.$pieces[$i].'<br/>';
$pizza = mysql_query("SELECT skill_id, skill_name FROM skill WHERE skill_id = '".$pieces[$i]."'",$conn);
while($p = mysql_fetch_assoc($pizza)){
echo '<b>'.$j.'</b>. '.$p['skill_name'].'<br/>';
}
$j++;
}
?>
</td>
<td align="center">
<input type="hidden" id="<?php echo $row_dosen['nik']; ?>" name="id_dosen" value="<?php echo $row_dosen['nik']; ?>"/>
<button id="<?php echo $row_dosen['nik']; ?>" class="btn btn-warning edtlec" type="button" data-toggle="modal" data-target="#editDosen"><i class="fa fa-gear"></i> <small>Edit</small></button>
</td>
<td align="center">
<button class="btn btn-danger delbutton" type="button" id = "<?php echo $row_dosen['nik']; ?>"><i class="fa fa-times"></i> <small>Delete</small></button>
</td>
</tr>
<?php
}
?>
MY javascript
$(document).ready(function(){
$("#lec_reg").click(function(){
var nik = $("#nik").val();
var name = $("#name").val();
var jurusan = $("#jurusan").val();
var status = $("#status").val();
var email = $("#email").val();
var phone = $("#phone").val()
var skill = $("#skill").val();
$.ajax({
type: "POST",
url:"inc_/regist_dosen.php",
data:"nik=" + nik +
"&name=" + name +
"&jurusan=" + jurusan +
"&status=" + status +
"&email=" + email +
"&phone=" + phone +
"&skill=" + skill,
success: function(data){
$("#loading").html('<center>Validating data... <img src="../../img/ajax-loader.gif"/></center>').show();
setTimeout(function() {
$("#loading").fadeIn();
setTimeout(function() {
$("#loading").slideUp('slow');
},2000);
$("#loading").html(data);
},1000);
}
});
});
$(function() {
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this Lecturer ? NIK : "+del_id)){
$.ajax({
type: "POST",
url: "inc_/delete_dosen",
data: info,
success: function(data){
$(".loading2").html('<center>Loading data... <img src="../../img/ajax-loader.gif"/></center>').show();
setTimeout(function() {
$(".loading2").fadeIn();
setTimeout(function() {
$(".loading2").slideUp('slow');
},4000);
$(".loading2").html(data);
},1000);
}
});
}
return false;
});
});
$(function() {
$(".edtlec").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var edit_id = element.attr("id");
//Built a url to send
var info = 'id_nik=' + edit_id;
$.ajax({
type: "POST",
url: "inc_/edit_dosen",
data: info,
success: function(data){
$('#editDosen').modal('show');
$("#response").html('<center>Loading data... <img src="../../img/ajax-loader.gif"/></center>').show();
setTimeout(function() {
$("#response").html(data);
},1000);
}
});
return false;
});
});
Finally my script now work on page 2 ++
The answer is
change to
$( document ).on( "click", ".delbutton", function() {
Because DataTables removes nodes from the DOM, event's might not be applied
credit
http://datatables.net/faqs#events
Thanks for all , especially Allan Jardin From datatables forum :)

Get the value of text box using jquery

I have the following script :
<script>
$(document).ready(function() {
$('#edit').click(function (){
//get
employee_id = $('#employee_id').val();
alert(employee_id);
html='';
$.ajax({
type: "GET",
url: "<?php echo base_url();?>administrator/admin/get_employee_details/"+employee_id,
dataType: "json",
success: function(response) {
console.log(response);
$( '#fname' ).val(response[0].f_name);
alert(response[0].amount);
$( '#sname' ).val(response[0].l_name);
$( '#lname' ).val(response[0].other_name);
$( '#expiry_date' ).val(response[0].id_no);
$( '#quantity_available').val(response[0].dob)
$( '#gender' ).val(response[0].gender);
$( '#maritalstatus').val(response[0].marital_status)
$( '#sex' ).val(response[0].gender);
},
error: function(data){
}
})
});
});
</script>
The script is supposed pick the employee_id value from the table below :
<tbody>
<?php foreach($employee_details as $employee ):?>
<tr class="odd gradeX">
<td><?php echo $employee['employee_name'];?></td>
<td ><?php echo $employee['id_no'];?></td>
<td><?php echo $employee['dob'];?></td>
<td><?php echo $employee['gender'];?></td>
<td ><?php echo $employee['marital_status'];?></td>
<td><?php echo $employee['phone_no'];?></td>
<td><?php echo $employee['email'];?></td>
<td ><?php echo $employee['date_added'];?></td>
<td><?php echo $employee['residence'];?></td>
<td ><?php echo $employee['next_of_kin_name'];?></td>
<td><?php echo $employee['next_of_kin_relation'];?></td>
<td><?php echo $employee['next_of_kin_phone_no'];?></td>
<td ><?php echo $employee['is_active'];?></td>
<td><?php echo $employee['department_name'];?></td>
<td><?php echo $employee['employee_class'];?></td>
<td><a class="edit" href="#edit_details" id="edit">Edit </a></td>
<td> <a class="delete" href="#delete_details" id="delete" > Delete Employee</a></td>
<input type="text" name="employee_id" id="employee_id" value="<?php echo $employee['employee_id'];?>"/>
</tr>
<?php endforeach;?>
</tbody>
which is a hidden text field (employee_id) in the table when I click the Edit button. But when I click the link , I get an empty result with no employee_id yet I can see the employee id in the text box. How can I get the employee id from the text box for each specific row?
Id of an element must unique, so inside the loop use class instead of id, also move the employee_id field to a td element
<td>
<a class="edit" href="#edit_details">Edit </a>
</td>
<td>
<a class="delete" href="#delete_details" > Delete Employee</a>
<input type="text" name="employee_id" value="<?php echo $employee['employee_id'];?>" />
</td>
then
$(document).ready(function () {
$('.edit').click(function () {
//get
var employee_id = $(this).closest('tr').find('input[name="employee_id"]').val();
alert(employee_id);
html = '';
$.ajax({
type: "GET",
url: "<?php echo base_url();?>administrator/admin/get_employee_details/" + employee_id,
dataType: "json",
success: function (response) {
console.log(response);
$('#fname').val(response[0].f_name);
alert(response[0].amount);
$('#sname').val(response[0].l_name);
$('#lname').val(response[0].other_name);
$('#expiry_date').val(response[0].id_no);
$('#quantity_available').val(response[0].dob)
$('#gender').val(response[0].gender);
$('#maritalstatus').val(response[0].marital_status)
$('#sex').val(response[0].gender);
},
error: function (data) {
}
})
});
});
The id attribute must be unique in your web page. You can't have 2 elements with the same id.
So for your links and your inputs, you must generate a different id for each row. For example you can try id="employee_id-<?php echo $employee['employee_id'];?>".
But you can keep the same classes for each link and input, and use it in your javascript script code.
Then you must change your code :
$('.edit').click(function() {
var employee_id = this.closest('tr').find('.employee_id').val();
});
Use class attribute instead of id because id cant be repeated.
<input type="text" name="employee_id" class="employee_id" value="<?php echo $employee['employee_id'];?>"/>
$('.edit').click(function() {
var id = this.closest('tr').find('input.employee_id').val();
});
In Id you will be able to get employee id

How to delete all entry from table using checkBox clickall after confirmation is true? jQuery Ajax PHP

I am trying to delete all records from the table using the checkbox. When the user checked the topmost checkbox, it will check all other checkboxes inside the loop then a confirmation box will appear about deleting the records. if the user click OK, the the all the records will be deleted using $.ajax, if he clicked Cancel, then, the page will return to the same state, and the checkboxes are not checked anymore.
<?php
include 'dbconn.php';
?>
<table border="1" >
<tr><td align="center" width="20"><input type="checkbox" name='checkALL' id='checkALL'></td><td>Name</td>
</tr>
<?php
$sql=mysql_query("SELECT * FROM names ORDER BY names ASC") or die(mysql_error());
while($rows=mysql_fetch_assoc($sql)){
?>
<tr>
<td><input type="checkbox" name="id[]" id="id[]" value="<?php print $rows['id'];?>">
</td><td>Name</td>
</tr>
<?php
}
?>
</table>
JQUERY
<script>
$(function(){
//click all
$('#checkALL').click(function(){
$(':checkbox').attr({checked: 'true'});
var del=confirm("You checked all the box. Delete All?");
if(del==true){
//delete here using $.ajax
}
else{
window.location.reload(false);
$('#checkAll').attr({checked: 'false'});
}
});
});
</script>
Place this in your if block.
$.ajax({
type: "GET",
url: '<php file which truncates table>',
success: function (data) {
if (data == 'truncated') {
alert('success');
} else {
alert('not truncated');
}
}
});
Return the string truncated from your php file on success.
Here U- PageUrl, A- Action on page, P- Parameter
if (confirm('Are you sure to delete this record?')) {
Operation(U, A, P);
}
function Operation(U, A, P) {
$.ajax({
type: "POST",
url: U + '/' + A,
data: P,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (r) {
var str = r.d;
}
});
}
You can use something like this in your HTML check all page
<html>
<head><title>Select/Delete ALL with jQuery/PHP</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<table border="1" cellpadding="5">
<tr>
<th>
<input type="checkbox" id="checkAll" />
</th>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="100" /></td>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="200" /></td>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="300" /></td>
</tr>
</table>
<script>
$(document).ready(function(){
var checked = false;
$('#checkAll').click(function(){
if (checked == false){
checked = true
} else {
checked = false
}
$('input.check').attr("checked",checked);
var confirmDelete=confirm("You checked all the box. Delete All?");
if (confirmDelete==true){
var csv = '';
$('.check').each(function() {
csv += $(this).attr("value") + ",";
});
$.ajax({
type: "POST",
url: "delete.php",
data: { tobeDeleted: csv }
}).done(function( msg ) {
console.log( "Data has been deleted: " + msg );
});
} else {
$('#checkAll').attr("checked", false);
$('input.check').attr("checked", false);
}
});
});
</script>
</body>
</html>
and use something like this in your PHP script
<?php
$postDeleted = substr($_POST['tobeDeleted'], 0, strlen($_POST['tobeDeleted'])-1);
$arrDeleted = explode(",", $postDeleted);
$sql = "DELETE FROM employee WHERE 1=1 ";
foreach($arrDeleted as $key=>$value){
$sql .= "OR employee_id = $value ";
}
echo $sql;
?>
if(del==true){
$.ajax({
type: "POST",
url: 'your_file_url',
async:false,
cache: false,
success: function(data){
if (data == 1) {
alert('success');
} else {
alert('Error');
}
}
});
}
In your php file, echo 1 for successful delete and 0 for some error

Passing variables using jquery and ajax php

i'm following this tutorial, so my issue is:
I have this code here, which are some tables.
<tr id="<?php echo $id; ?>" class="edit_tr">
<td class="edit_td">
<span id="first_<?php echo $id; ?>" class="text"><?php echo $kodi; ?></span>
<input type="text" value="<?php echo $kodi; ?>" class="editbox" id="first_input_<?php echo $id; ?>" />
</td>
<td class="edit_td">
<span id="last_<?php echo $id; ?>" class="text"><?php echo $vlera; ?></span>
<input type="text" value="<?php echo $vlera; ?>" class="editbox" id="last_input_<?php echo $id; ?>"/>
</td>
</tr>
Now, this is the script:
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#first_"+ID).hide();
$("#last_"+ID).hide();
$("#first_input_"+ID).show();
$("#last_input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var kodi=$("#first_input_"+ID).val();
var vlera=$("#last_input_"+ID).val();
var dataString = 'id='+ ID +'&kodi='+kodi+'&vlera='+vlera;
$("#first_"+ID).html('<img src="load.gif" />'); // Loading image
if(first.length>0&& last.length>0)
{
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#first_"+ID).html(first);
$("#last_"+ID).html(last);
I'm not passing variables right maybe..because it won't save them, the query won't excecute.
Thanks
The easiest way in jQuery to pass your form fields in ajax is by using serialize:
data: $("form").serialize();
An additional problem is that you are using two variables, first and last but you are not defining them anywhere.
Try this code:
$(function() { // This makes the same than $(document).ready();
$(".edit_tr").each(function() { // Instead of assign the click event, we loop through each element
var $element = $(this);
var id = this.id;
var $first = $('#first_' + id);
var $last = $('#last_' + id);
var $firstInput = $('#first_input_' + id);
var $lastInput = $('#last_input_' + id);
$element.click(function() {
$first.hide();$last.hide();
$firstInput.show();$lastInput.show();
}).change(function() {
$first.html('<img src="load.gif" />');
// Here you have an if, but those elements are not defined in the script...
// if (first.length > 0 && last.length > 0) {
$.post("table_edit_ajax.php", {
id : id,
kodi : $firstInput.val(),
vlera : $lastInput.val()
}, function(html) {
// Here again the two vars not defined
//$first.html(first);
//$last.html(last);
});
// }
});
});
});

Categories