Checkbox Data Dynamically Save to Database on Click - php

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.

Related

Instant Checkbox update on sql rows with ajax and jquery

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

PHP / SQL: Multiple delete unsucessful

currently I have created a system that can perform multiple delete actions for a list of data rows that fetch from a SQL database and display at dashboard_engineer.php. Each data row contains a delete button. Each row also has a checkbox that enables the user to delete selected data rows. At the bottom of the data rows, there's a button to delete all the selected data rows.
My problem is on multiple delete, lets say, if I select two data rows, (id 4 and 5) it will only delete one ID.
Below is my code
dashboard_engineer2.php
<?php
if(isset($_REQUEST['from'], $_REQUEST['to'], $_REQUEST['team'])){
$from = $_REQUEST['from'];
$to = $_REQUEST['to'];
$team = $_REQUEST['team'];
$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid
WHERE ot_report.status = 'yes' AND ot_users.team_id = :team AND report_date BETWEEN :from
AND :to ORDER BY ot_report.report_id DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql->bindParam(':team', $team);
$sql->bindParam(':from', $from);
$sql->bindParam(':to', $to,);
$sql -> execute();
if($sql->rowCount() > 0){
echo'
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th width = "10%"><input type="checkbox" id="checkAl"> All</th>
<th width = "3%">id</th>
<th width = "15%">Date</th>
<th width = "25%">Supervisor</th>
<th width = "30%">Task Name</th>
<th width = "10%">Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$status=$row['report_status'];
if($status=="Pending"){
$color="color:blue";
}
else {
$color="color:green";
}
$report_id = $row["report_id"];
echo'<tr>';
echo '<td><input type="checkbox" id="checkItem" name="check[]" value="'.$report_id.'"></td>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$row['report_date'].'</td>';
echo '<td>'.$row["fullname"].'</td>';
echo '<td>'.$row["task_name"].'</td>';
echo '<td align="center" style='.$color.'><strong>'.$status.'</strong></td>';
echo '<td align="center">';
echo '<form action = "view_task/view_task.php" method = "post" target="_blank">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-primary">View</button>';
echo '</form>';
echo '</td>';
echo '<td align="center">';
echo "<form action = 'remove2.php' method = 'post' onClick=\"return confirm('Do you want to remove this reports?')\">";
echo '<input type = "hidden" name = "from" value = "'.$from.'">';
echo '<input type = "hidden" name = "to" value = "'.$to.'">';
echo '<input type = "hidden" name = "team" value = "'.$team.'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Remove</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
$i++;
}
echo '<tr>';
echo '<td>';
echo "<form action = 'delete_selected.php' method = 'post'>";
echo '<input type="hidden" id="checkItem" name="check[]" value="'.$report_id.'">';
echo '<button type="submit" class="btn-danger btn-sm">DELETE</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
}
}
?>
delete_selected.php
<?php
include("../../../config/configPDO.php");
include("../../../config/check.php");
$checkbox = $_POST['check'];
for($i=0;$i<count($checkbox);$i++){
$report_id = $checkbox[$i];
$sql = "UPDATE ot_report SET status = 'no' WHERE report_id=:report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php");
}
?>
Can anyone help me to solve this problem? Thanks
OK - the following is based upon the question's code but in order to build a working demo it has been generalised. The important thing here is the use of Javascript to maintain the list of IDs selected ( either by clicking the select-all checkbox or by clicking individual checkboxes. Please ignore the content generated in the form - the dates are spurious and meaningless to this example.
You could copy this and create a test page which should run OK - the PHP that generates the pseudo SQL is simply to display the statements that would be executed and not how it should be executed ( should be as per question, prepared statement )
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( isset( $_POST['ids'] ) ){
$items=explode( ',', $_POST['ids'][0] );
foreach($items as $id){
$sql=sprintf('UPDATE ot_report SET status="no" WHERE report_id=%d',$id);
echo $sql . '<br />';
}
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<table>
<?php
for( $i=1; $i <= 10; $i++ ){
/* example data for dates... */
$hrs=mt_rand(1,24);
$mins=mt_rand(0,60);
$secs=mt_rand(0,60);
$month=mt_rand(1,12);
$day=mt_rand(1,28);
$year=mt_rand(2000,2020);
$from=date('y-m-d',mktime($hrs,$mins,$secs,$month,$day,$year));
$to=date('y-m-d',mktime($hrs+3,$mins+20,$secs,$month,$day,$year));
printf('
<tr>
<td><input type="checkbox" name="check[]" value="%1$d" /></td>
<td>Some data %1$d</td>
<td>
<form method="post">
<input type="hidden" name="from" value="%2$s" />
<input type="hidden" name="to" value="%3$s" />
<input type="hidden" name="id" value="%1$d" />
<input type="submit" />
</form>
</td>
</tr>', $i, $from, $to );
}
?>
</table>
<form method='post'>
<input type='checkbox' name='selectall' value='Select-All' />
<input type='hidden' name='ids[]' />
<input type='button' name='sub-delete' value='Update selected' />
</form>
<script>
let ids=document.querySelector('input[type="hidden"][name="ids[]"]');
let tmp=[];
document.querySelector('[name="selectall"]').addEventListener('change',function(e){
let col=document.querySelectorAll('[name="check[]"]');
col.forEach(chk=>{
chk.checked=this.checked;
if( this.checked )tmp.push(chk.value)
else tmp.splice(tmp.indexOf(chk.value),1)
});
});
document.querySelectorAll('[name="check[]"]').forEach( chk=>{
chk.addEventListener('change',function(e){
if( this.checked )tmp.push(this.value)
else tmp.splice( tmp.indexOf(this.value),1);
});
});
document.querySelector('[name="sub-delete"]').addEventListener('click',function(e){
ids.value=tmp.join(',')
this.parentNode.submit()
});
</script>
</body>
</html>
Will generate something akin to:
UPDATE ot_report SET status="no" WHERE report_id=10
UPDATE ot_report SET status="no" WHERE report_id=8
UPDATE ot_report SET status="no" WHERE report_id=6
UPDATE ot_report SET status="no" WHERE report_id=4
Quickly trying to adapt this example with your code :
<?php
if(isset($_REQUEST['from'], $_REQUEST['to'], $_REQUEST['team'])){
$from=$_REQUEST['from'];
$to =$_REQUEST['to'];
$team=$_REQUEST['team'];
$result='';
$query="SELECT * FROM ot_report
LEFT JOIN ot_users ON ot_report.badgeid=ot_users.badgeid
WHERE ot_report.status='yes' AND ot_users.team_id=:team AND report_date BETWEEN :from AND :to
ORDER BY ot_report.report_id DESC";
$sql=$conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql->bindParam(':team', $team);
$sql->bindParam(':from', $from);
$sql->bindParam(':to', $to);
$sql->execute();
if($sql->rowCount() > 0){
echo'
<table class="table-bordered" width="100%">
<thead>
<tr>
<th width="10%"><input type="hidden" name="selectall" value="Select-All">All</th>
<th width="3%">id</th>
<th width="15%">Date</th>
<th width="25%">Supervisor</th>
<th width="30%">Task Name</th>
<th width="10%">Status</th>
<th colspan="2" width="7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row=$sql->fetch(PDO::FETCH_ASSOC)){
$status=$row['report_status'];
if($status=="Pending"){
$color="color:blue";
} else {
$color="color:green";
}
$report_id=$row["report_id"];
echo'
<tr>
<td><input type="checkbox" name="check[]" value="'.$report_id.'"></td>
<td>'.$report_id.'</td>
<td>'.$row['report_date'].'</td>
<td>'.$row["fullname"].'</td>
<td>'.$row["task_name"].'</td>
<td align="center" style='.$color.'><strong>'.$status.'</strong></td>
<td align="center">
<form action="view_task/view_task.php" method="post" target="_blank">
<input type="hidden" name="report_id" value="'.$report_id.'">
<button type="submit" class="btn-primary">View</button>
</form>
</td>
<td align="center">
<form action="remove2.php" method="post" onsubmit="return confirm(\'Do you want to remove this reports?\')">
<input type="hidden" name="from" value="'.$from.'">
<input type="hidden" name="to" value="'.$to.'">
<input type="hidden" name="team" value="'.$team.'">
<input type="hidden" name="report_id" value="'.$report_id.'">
<button type="submit" class="btn-danger">Remove</button>
</form>
</td>
</tr>';
$i++;
}
echo '
<tr>
<td>
<form action="delete_selected.php" method="post">
<input type='hidden' name='ids[]' />
<input type='button' name='sub-delete' value='DELETE' />
</form>
</td>
</tr>';
}
}
?>
<script>
let ids=document.querySelector('input[type="hidden"][name="ids[]"]');
let tmp=[];
document.querySelector('[name="selectall"]').addEventListener('change',function(e){
let col=document.querySelectorAll('[name="check[]"]');
col.forEach(chk=>{
chk.checked=this.checked;
if( this.checked )tmp.push(chk.value)
else tmp.splice(tmp.indexOf(chk.value),1)
});
});
document.querySelectorAll('[name="check[]"]').forEach( chk=>{
chk.addEventListener('change',function(e){
if( this.checked )tmp.push(this.value)
else tmp.splice( tmp.indexOf(this.value),1);
});
});
document.querySelector('[name="sub-delete"]').addEventListener('click',function(e){
ids.value=tmp.join(',')
this.parentNode.submit()
});
</script>
and
delete_selected.php
<?php
include("../../../config/configPDO.php");
include("../../../config/check.php");
$checkbox=explode( ',', $_POST['ids'][0] );
for($i=0;$i < count($checkbox); $i++){
$report_id=$checkbox[$i];
$sql="UPDATE ot_report SET status='no' WHERE report_id=:report_id";
$query=$conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php");
}
?>

PHP / AJAX: Delete unsuccessful at AJAX

Currently, I created a system that has AJAX function. To be more clear, below is my current process flow:
1) dashboard.php will display 3 select option which is team, time from and time to
2) user need to complete all 3 select option and click button 'search'. At this point where AJAX (range.php).
3) All data row will be listed and each data have a delete button. User can delete data based on data row.
My problem is, the data is not deleted.
Below is my current code.
dashboard.php
<select class="form-control" name="team" id="team">
<option value="">Please select...</option>
<?php foreach ($data as $row2): ?>
<option value= <?php echo $row2["team_id"]; ?> <?php echo (($_GET["team"] ?? '') == $row2["team_id"]) ? 'selected' : ''; ?> ><?php echo $row2["fullname"]; ?></option>
<?php endforeach ?>
</select>
<td width="1%"></td>
</td>
<td width="20%"><input type="text" name="from" id="from" class="form-control" placeholder="From" value = '<?php echo $_GET["from"] ?? ''; ?>'></td>
<td width="1%"></td>
<td width="20%"><input type="text" name="to" id="to" class="form-control" placeholder="To" value = '<?php echo $_GET["to"] ?? ''; ?>'></td>
<td width="1%"></td>
<td width="10%"><input type="button" name="range" id="range" value="Search" class="btn btn-primary"><td>
</tr>
</table><br>
<div id = "dashboard">
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from").datepicker().attr("autocomplete", "off");;
$("#to").datepicker().attr("autocomplete", "off");;
});
$('#range').click(function(){
var from = $('#from').val();
var to = $('#to').val();
var team = $('#team').val();
if(from != '' && to != '' && team != '')
{
$.ajax({
url:"range.php",
method:"POST",
data:{from:from, to:to, team:team},
success:function(data)
{
$('#dashboard').html(data);
}
});
}
else
{
alert("Please select both team and date range");
}
});
if($('#from').val() && $('#to').val() && $('#team').val()){
$('#range').click();
}
});
</script>
range.php (AJAX)
<?php
require_once "../../../config/configPDO.php";
require_once "../../../config/check.php";
$email = $_SESSION['login_user'];
if(isset($_POST["from"], $_POST["to"], $_POST["team"]))
{
$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST['team']."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql -> execute();
if($sql->rowCount() > 0)
{
echo'
<form method="post" action="">
<div class="row" style="height: 300px; overflow-y: scroll;">
<div class="col-lg-12 grid-margin stretch-card">
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th>id</th>
<th>Date</th>
<th>Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
while($row = $sql->fetch(PDO::FETCH_ASSOC))
{
$datereport = $row['report_date'];
$datereport2 = strtotime($datereport);
$report_date = date('d M Y', $datereport2);
$report_id = $row["report_id"];
echo'<tr>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$report_date.'</td>';
echo '<td align="center">';
echo '<a class="btn-view btn-primary btn-sm" href="view_task/view_task.php?report_id='. $report_id .'" data-toggle="tooltip">View</a></td>';
echo '<td align="center">';
echo '<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">';
echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Delete</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
}
}
delete_ajax.php
<?php
require_once '../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$sql = "DELETE FROM ot_report WHERE report_id=:report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php?from='".$_POST["from"]."'&to='".$_POST["to"]."' &team='".$_POST["team"]."'");
?>
Can anyone knows what is the problem? The data cannot deleted!. Help anyone
maybe this is because in the range.php file you have 2 form tags
first is outside while function
<form method="post" action="">
and second one is in while function
<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">
try removing the first one

onchange dropdown show checkbox is checked in php

code:
<script>
$(document).ready(function(){
$(".menu").click(function(){
ids = $('.menu:checked').map(function() {
return this.id;
}).get().join(',');
console.log(ids);
$("#ids").val(ids);
});
});
</script>
<?php
if(isset($_POST['submit']))
{
$adminid = $_POST['admin'];
$menuids = explode(",", $_POST['ids']);
foreach ($menuids as $idd)
{
$sql = "update menu set admin_id = concat(admin_id,'$adminid',',') where id = '$idd'";
$result = mysqli_query($link,$sql);
}
if($result == true)
{
$msg .= "<p style='color:green'>successfull</p>";
}
else
{
$msg .= "<p style='color:red'>error!</p>";
}
}
?>
<form method="post">
<select name="admin" id="admin">
<option value="">---Select Admin---</option>
<?php
$sql = "select * from admin";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['firstname']?></option>
<?php
}
?>
</select>
<table>
<tr>
<th>Share</th>
<th>Menu Name</th>
</tr>
<?php
$query = "select * from menu";
$results = mysqli_query($link,$query);
while ($fetch = mysqli_fetch_array($results))
{
?>
<tr>
<td>
<input type="checkbox" class="menu" id="<?php echo $fetch['id']; ?>" name="menuid" />
</td>
<td>
<?php echo $fetch['menu_name']; ?>
</td>
</tr>
<?php
}
?>
</table>
<input type="text" name="ids" id="ids" value=""/>
<input type="submit" name="submit" id="submit" />
</form>
In this code I am update a table having name menu in database. Now, I want to check only those checkbox where admin_id like ,1, or ,2, which is update by query. How can I fix this issue ?please please help.
Thank You
while ($fetch = mysqli_fetch_array($results))
{
?>
<tr>
<td>
<input type="checkbox" class="menu" value="<?php if($fetch['id']==1 or
$fetch['id']==2 ) { echo "checked";} else{} ?>" name="menuid" />
</td>
<td>
<?php echo $fetch['menu_name']; ?>
</td>
</tr>
<?php
}
?>

multiple submit on same page with php ajax

<div id="home">
<div class="container">
<form action="" method="post">
<b><font color = "000099"><select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select></font></b>
<b><font color = "000099"><select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select></b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /> </b>
<input type="submit" value="GO"/></font><br>
</form>
<font color = "339933"><b>
</b></font>
<p><div id="body">
<table width="98%" border="1">
<tr></tr>
<tr>
<td><font color = "339933"><b>Name</td>
<td><font color = "339933"><b>E-Mail </td>
<td><font color = "339933"><b>Access</td>
<td><font color = "339933"><b>Update </td>
</tr>
<?php
$read = $_POST['read'];
If($read == 'New'){
$read = '0';
}
If($read == 'Archive'){
$read = '1';
$arc = 'AND date < CURDATE() - INTERVAL 90 DAY';
}
$category = $_POST['category'];
$value = $_POST['value'];
if($category == 'Name'){
$where = " where name like '%$value%' ";
}else if($category == 'E-mail'){
$where = " where Email like '%$value%' ";
}else if($category == 'Employee'){
$where = " where Email like '%$value%' ";
}else if($category == 'Customer'){
$where = " where Email not like '%$value%' ";
}
$select = 'SELECT *';
$from = ' FROM users';
if($where == ''){
$where = ' WHERE TRUE ';
}
$order = " order by id desc limit 100";
if($read == '0'){
$sql = $select . $from . $where . $order ;
}else{
$sql = $select . $from . $where . $arc . $order ;
}
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set)) {
?>
<tr>
<form method="post" name="forms" action="">
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access']; ?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</form>
<?php } ?>
</table>
</div>
</body>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
alert('asfsfsds');
var ID = $(this).attr("id");
var dataString1 = 'msg_id='+ ID;
var mail = $("#remail").val();
var mailid = 'remail='+ mail;
var textcontent = $("#access_rights").val();
var dataString = 'access_rights='+ textcontent;
if(textcontent==''){
alert("Enter some Value..");
$("#access_rights").focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: dataString,mailid,dataString1,
cache: true,
success: function(html){
document.getElementById('access_rights').value='';
$("#access_rights").focus();
}
});
}
return false;
});
});
</script>
</html>
Above is my php ajax code. I want to one field in mysql database by ajax.
There are multiple submit button on the page. Let me explain you properly.
Below code is used for sorting the value on the page. This value retrieve from database. This is working fine. I can get the data from database and it is showing in the same page.
<form action="" method="post">
<b><font color = "000099">
<select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select>
</font></b>
<b><font color = "000099">
<select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select>
</b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /></b>
<input type="submit" value="GO"/></font><br>
</form>
In below code data is showing from database and one text box and submit button will display in table.
<form method="post" name="forms" action="">
<tr>
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access'];?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</tr>
</form>
I want user with special permission can update the value by ajax because there could be multiple rows and it is not good to page get refreshed each time.
At the moment after clicking on update button ajax event not firing.
Can anybody advise me on this. I am not good in ajax.
There may be other issues, but the following line is syntactically incorrect:
data: dataString,mailid,dataString1,
That is not how you concatenate a string in Javascript. Plus, you would need to separate the name=value pairs with ampersands.
Instead of concatenating a string, you can use an object and let JQuery do the concatenating:
data: {
'access_rights': $("#access_rights").val(),
'remail': $("#remail").val(),
'msg_id': $(this).attr("id")
},
UPDATE:
You don't have an element with id="access_rights. You do have an element with id="remail", but you create that element in a loop, so you will have multiple elements with that id.
You need to get the values of the elements that are in the same row as the clicked submit button. You can't do that using id values. Instead, you use .closest('tr') on the button element to get the surrounding row. You can then use .find() on the row element to get the values in that row.
Change:
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
To:
<td><font color="Black" class="remail"><?php echo $row['Email']; ?></td>
Then you can have:
$(".submit_button").click(function() {
var $submitBtn = $(this),
$row = $(this).closest('tr'),
$accessRights = $row.find("input[name=access_rights]"),
accessRights = $accessRights.val();
if (accessRights == ''){
alert("Enter some Value..");
$accessRights.focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: {
'access_rights': accessRights,
'remail': $row.find(".remail").text(),
'msg_id': $submitBtn.attr("id")
},
cache: true,
success: function(html){
$accessRights.val('').focus();
}
});
}
return false;
});
You are also missing the closing </tr> tag.

Categories