Apologies if this question has been asked previously.
I am currently generating a basic table using PHP and have one cell where a user can add a comment.
When the user types a comment into the editable cell it saves it to the database table "TechComment column".
I want the editable cell to "disable editing" after the user entered the comment.
My code below:
Table Code
require_once "../linkd.php";
$sql = "select * from DispatchTech where Technician = ? and convert(date, Inserted) = convert(date,
getdate()) order by Completed ASC, DoneWhen";
$ses = $_SESSION['Username'];
$par = array($ses);
$stmt = sqlsrv_query($conn, $sql, $par);
if($stmt){
$count = 1;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$id = $row['Id'];
$txt = $row['TechComment'];
?>
<tr>
<?PHP
if($row['Completed'] == NULL){
print "<td><button onclick=location.href='complete.php?Id=".$row['Id']."'>Complete</button></td>";
}
elseif($row['Completed'] != NULL){
print '<td><span align="center" style="font-size:15px;">✅</span></td>';
}
if($row['Area'] == NULL){
print "<td><button onclick=location.href='arrive.php?Id=".$row['Id']."'>On Site</button></td>";
}else{
print "<td>";
print date_format(new DateTime($row['Area']), "H:i:s");
print "</td>";
}
?>
<td><?php echo $row['TermID']; ?></td>
<td><?php echo $row['Location']; ?></td>
<td><?php echo $row['DMRef']; ?></td>
<td><?php echo $row['Error']; ?></td>
<td><?php echo $row['Description']; ?></td>
<td><?php echo date_format($row['Inserted'], "H:i:s") ?></td>
<td><div contentEditable='true' class="edit" id='TechComment_<?php echo $id; ?>'><?php echo $txt; ?>
</div> </td>
<td><?php echo $row['Timeframe']; ?></td>
</tr>
<?PHP
$count ++;
}
}
?>
Jquery/Ajax Code:
$(document).ready(function(){
$('.edit').click(function(){
$(this).addClass('editMode');
});
$(".edit").focusout(function(){
$(this).removeClass("editMode");
var id = this.id;
var split_id = id.split("_");
var field_TechComment = split_id[0];
var edit_id = split_id[1];
var value = $(this).text();
$.ajax({
url: 'update.php',
type: 'post',
data: { field:field_TechComment, value:value, id:edit_id },
success:function(response){
console.log('Save successfully');
}
});
});
});
I found this short jquery script that will do the trick but can't get it to work.
$('.edit').editable(function (value, settings) {
return value;
});
Might it be because i'm using ajax?
I am not that familiar with ajax.
Any help will be greatly appreciated.
You can achieve it by setting contentEditable to false in your ajax response, like:
$(".edit").focusout(function(){
$(this).removeClass("editMode");
var id = this.id;
var split_id = id.split("_");
var field_TechComment = split_id[0];
var edit_id = split_id[1];
var value = $(this).text();
$.ajax({
url: 'update.php',
type: 'post',
data: { field:field_TechComment, value:value, id:edit_id },
success:function(response){
console.log('Save successfully');
$('#'+id).prop('contenteditable', false );
}
});
});
Related
so i try showing data with ajax and get filter it by values...
it came work when i just show all data
but i want to make show data is filter by dropdown values and it require post for getting the dropdown selected values
Then when i got done i can make the POST function get work on console, and the response that i get is not problem at all
but the get function for view data is not working
so the data wont load...
prepro.php for dropdown function (seems not problem at all)
<select id="data_latih">
<option value="" selected="selected">Pilih Dokumen keberapa</option>
<?php
$sql = "SELECT DISTINCT dokumen FROM dt_latih ";
$resultset = mysqli_query($connection, $sql) or die("database error:". mysqli_error($connection));
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["dokumen"]; ?>"><?php echo $rows["dokumen"]; ?></option>
<?php } ?>
</select>
prepro.php on ajax function
function viewData(){
$.ajax({
url: 'proseslabel.php?p=view',
method: 'GET'
}).done(function(data){
$('tbody').html(data)
tableData()
})
}
function tableData(){
$('#tabledit').Tabledit({
url: 'proseslabel.php',
eventType: 'dblclick',
editButton: true,
deleteButton: false,
hideIdentifier: false,
buttons: {
edit: {
class: 'btn btn-sm btn-warning',
html: '<span class="glyphicon glyphicon-pencil"></span> Edit',
action: 'edit'
},
save: {
class: 'btn btn-sm btn-success',
html: 'Save'
}
},
columns: {
identifier: [0, 'id_latih'],
editable: [[16, 'label', '{"1": "1", "2": "2", "3": "3", "4": "4", "5": "5", "6": "6"}']]
},
onSuccess: function(data, textStatus, jqXHR) {
viewData()
},
onFail: function(jqXHR, textStatus, errorThrown) {
console.log('onFail(jqXHR, textStatus, errorThrown)');
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
onAjax: function(action, serialize) {
console.log('onAjax(action, serialize)');
console.log(action);
console.log(serialize);
}
});
}
$("#data_latih").change(function() {
var id = $(this).find(":selected").val();
$.ajax({
url: 'proseslabel.php?p=view',
method:"POST",
data: {id:id},
dataType: "json",
cache: false,
success: function(data) {
console.log(data);
$('tbody').html(data);
viewData;
tableData();
}
});
});
</script>
proseslabel.php for showing data
$page = isset($_GET['p'])? $_GET['p'] : '' ;
if($page=='view'){
if(isset($_POST["id"]))
{
$result = $mysqli->query("SELECT * FROM dt_latih ");
while($row = $result->fetch_assoc()){
?>
<tr>
<td><?php echo $row['id_latih'] ?></td>
<td><?php echo $row['kalimat'] ?></td>
<td><?php echo $row['x1'] ?></td>
<td><?php echo $row['x2'] ?></td>
<td><?php echo $row['x3'] ?></td>
<td><?php echo $row['x4'] ?></td>
<td><?php echo $row['x5'] ?></td>
<td><?php echo $row['x6'] ?></td>
<td><?php echo $row['x7'] ?></td>
<td><?php echo $row['x8'] ?></td>
<td><?php echo $row['x9'] ?></td>
<td><?php echo $row['x10'] ?></td>
<td><?php echo $row['x11'] ?></td>
<td><?php echo $row['x12'] ?></td>
<td><?php echo $row['x13'] ?></td>
<td><?php echo $row['x14'] ?></td>
<td><?php echo $row['label'] ?></td>
</tr>
<?php
}
}
} else{
// Basic example of PHP script to handle with jQuery-Tabledit plug-in.
// Note that is just an example. Should take precautions such as filtering the input data.
header('Content-Type: application/json');
$input = filter_input_array(INPUT_POST);
if ($input['action'] == 'edit') {
$mysqli->query("UPDATE dt_latih SET label='" . $input['label'] . "' WHERE id_latih='" . $input['id_latih'] . "'");
} else if ($input['action'] == 'delete') {
$mysqli->query("UPDATE tabledit SET deleted=1 WHERE id_latih='" . $input['id_latih'] . "'");
} else if ($input['action'] == 'restore') {
$mysqli->query("UPDATE tabledit SET deleted=0 WHERE id_latih='" . $input['id_latih'] . "'");
}
mysqli_close($mysqli);
echo json_encode($input);
}
the data just wont load , but in console inspect element , i get all the values that i want to echo
In your viewData() function, you should define your parameters in the data option of the AJAX call instead of in the url. Like this:
function viewData(){
$.ajax({
url: 'proseslabel.php',
method: 'GET',
data: {p:'view'}
}).done(function(data){
$('tbody').html(data);
tableData();
})
}
I know that this question might have been asked before, but I can't figure it out.
AJAX is passing the selected date to PHP and it should dynamically update this $select with the data from AJAX and update the query made to teh database. But $_POST['date'] seems to be empty and nothing is happening.
AJAX
$(window).ready(function(event) {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){ dd='0'+dd; }
if(mm<10){ mm='0'+mm; }
var today = yyyy+'-'+mm+'-'+dd; // document.getElementById("DATE").value = today;
selectedDate = today; // selectedDate = '2016-04-17';
var options = {
selectedDate: selectedDate,
onSelectedDateChanged: function(event, date) {
var d = new Date(date);
passDate(d);
}
};
passDate(new Date(selectedDate));
$('#paginator').datepaginator(options);});
function passDate(d) {
date = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
console.log(date);
$.ajax({
data: date,
type: "POST",
url: "php/table_body.php"
});};
PHP
<?php
$select = $_POST['data'];
$sql_query="SELECT * FROM users where date = '$select'";
// $sql_query="SELECT * FROM users WHERE date = '2017-05-12'";
$result_set=mysql_query($sql_query);
if(mysql_num_rows($result_set)>0)
{
while($row=mysql_fetch_row($result_set))
{
?>
<tr>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
<td><?php echo $row[3]; ?></td>
<td><?php echo $row[4]; ?></td>
<td><?php echo $row[5]; ?></td>
<td><?php echo $row[6]; ?></td>
<td><?php echo $row[7]; ?></td>
<td align="center"><span class="glyphicon glyphicon-edit"> Edit</td>
<td align="center"><span class="glyphicon glyphicon-trash"> Delete</td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td colspan="5">No Data Found !</td>
</tr>
<?php
}
Can you help figure how to fix it. Thank you
In the ajax javascript:
data: { date: date },
You didn't define the variable key for the date.
Also change in the php
$select = $_POST['date'];
And as suggested in the comments code for SQL injection protection.
check your parameter on $.ajax for the data, it should be like
$.ajax({
url: "php/table_body.php",
method: "POST",
data: { date: date}
});
for more information visit this link for ajax ref http://api.jquery.com/jquery.ajax/
I want to add a delete button to this table, to delete the query from Database. I have the Ajax and PHP codes here :
<?php
require_once 'dbconfig.php';
$stmt = $pdo->prepare("SELECT * FROM test");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['server']; ?></td>
<td><?php echo $row['reference']; ?></td>
<td align="center"><a id="<?php echo $row['id']; ?>" class="delete-link" href="#" title="Delete">
<img src="images/delete.png" width="20px" />
</a></td>
</tr>
<?php
}
?>
the ajax :
$(document).ready(function(){
/* Data Delete Starts Here */
$(".delete-link").click(function()
{
var id = $(this).attr("id");
var del_id = id;
var parent = $(this).parent("td").parent("tr");
if(confirm('Sure to Delete ID no = ' +del_id))
{
$.post('delete.php', {'del_id':del_id}, function(data)
{
parent.fadeOut('slow');
});
}
return false;
});
/* Data Delete Ends Here */
});
delete.php :
<?php
include_once 'dbconfig.php';
if($_POST['del_id'])
{
$id = $_POST['del_id'];
$stmt=$db_con->prepare("DELETE FROM test WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
?>
The row selected doesn't seem to get DELETED in the DB ... i have no error too.
You had pass data incorrectly . Please try this
$(document).ready(function()
{
$('table#delTable td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "view.php",
data: {id:id},
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
});
I'm working with a table in Bootstrap and one of the columns is for a checkbox. The table is filled with the values from a mysql db. In the db the column for the checkbox has a value of 1, or 0. I want the checkbox to be checked if the value is 1. I have this code, but it only works for the first checkbox. How can i use it for all checkboxes? This is my code.
<tbody>
<?php while($row = $sql->fetch()) { ?>
<tr>
<td><?php echo $row['Opleiding_ID']; ?></td>
<td><?php echo $row['Opleiding']; ?></td>
<?php $checked = $row['Hidden']; ?>
<script type="text/JavaScript">
$(document).ready(function(){
var arr<?php echo $row["Opleiding_ID"]; ?> = <?php echo json_encode($checked); ?>;
if (arr<?php echo $row["Opleiding_ID"]; ?> == "1") {
$("#mycheckbox<?php echo $row["Opleiding_ID"]; ?>").prop('checked', true);
} else {
$("#mycheckbox<?php echo $row["Opleiding_ID"]; ?>").prop('checked', false);
}
});
</script>
<td><input type="checkbox" id="mycheckbox<?php echo $row["Opleiding_ID"]; ?>" name="checks" value="" class="check"></td>
</tr>
<?php } ?>
</tbody>
$(document).ready(function() {
var arr = <?php echo json_encode($checked); ?>;
$.each(arr, function(index) {
if (arr[index] == "1") {
$("#mycheckbox").prop('checked', true);
}
});
});
Untested & probably buggy. But this is the right approach you should take. Run the elements in a loop.
if you have an auto increment id you can echo it inside the javascript code like this
<script type="text/JavaScript">
$(document).ready(function(){
var arr<?php echo $row["id"]; ?> = <?php echo json_encode($checked); ?>;
$.each(arr<?php echo $row["id"]; ?>, function(index) {
if (arr<?php echo $row["id"]; ?>[index] == "1") {
$(".check<?php echo $row["id"]; ?>").prop('checked', true);
}
});
});
</script>
<td><input type="checkbox" id="mycheckbox" name="checks" value="" class="check<?php echo $row["id"]; ?>"></td>
</tr>
<?php } ?>
</tbody>
if you re going to follow that code you should make a variable like this $id = $row["id"]; to type less
if you generate your table dynamically you can set your checkbox value there something like this .
JS :
$(document).ready(function(){
// your arr from php
var arr = [{'value' : 0 , 'name' :'Itme1' , 'description':'description1'},
{'value' : 1 , 'name' :'Itme2' , 'description':'description2'},
{'value' : 0 , 'name' :'Itme3' , 'description':'description3'},
{'value' : 1 , 'name' :'Itme4' , 'description':'description4'}];
var tableContent = '';
$.map(arr, function (item) {
checked= (item.value) ? "checked" : "" ;
tableContent+='<tr><td><input type="checkbox"'+checked+ '></td><td>' + item.name + '</td><td>' + item.description + '</td><td><input type="button" value="Edit" ></td></tr>';
});
$("#myTbody").html(tableContent);
});
Example : http://jsfiddle.net/tg5op333/39/
There is a div element :
...
<div id="liste_secteurs"></div>
...
<script type="text/javascript">
$(document).ready(function() {
rechercheSecteursEtProduits(0); // setting the div's content
$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
});
});
function rechercheSecteursEtProduits(pn){
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_user="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html); // this is the div element
}
</script>
Code of ListerProduitsUserParSecteursAjax.php :
<?php
... // getting database data
?>
<p>Total : <?php echo $nr; ?></p>
<div><img src="<?php echo HTTP_ICON.'plus.png'; ?>" /></div>
<?php echo $paginationDisplay; ?>
<table id="table" class="data display " >
<thead style="background-color:#CCC">
<tr>
<th><?php echo _getText("service.produit.form.secteur_activite");?></th>
<th><?php echo _getText("service.produit.form.titre");?></th>
<th></th>
<th><?php if($data["secteur"]["cnt"] > 0){ ?><input type="checkbox" id="check_all"><?php }?></th>
</tr>
</thead>
<tbody style="background-color:#FFF">
<?php
if($data["secteur"]["cnt"] > 0){
for($i=0;$i<$data["secteur"]["cnt"];$i++){?>
<tr class="odd gradeX">
<td><?php echo $data["secteur"][$i]["secta_lib_fr"] ?></td>
<td><?php echo $data["secteur"][$i]["produit_lib"] ?></td>
<td align="center" style="vertical-align:middle"><img src="<?php echo HTTP_ICON.'edit.png'; ?>" alt="<?php echo _getText('main.btn.modifier'); ?>" style="height:10px;width:10px;" /></td>
<td align="center" style="vertical-align:middle"><input type="checkbox" id="prod_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_produit']; ?>"><input type="hidden" id="secteur_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_secteur']; ?>"></td>
</tr>
<?php } ?>
<?php
}
else{
?>
<tr class="odd gradeX">
<td colspan="4" align="center"><b><?php echo _getText('main.liste.no_data'); ?></b></td>
</tr>
<?php }?>
</tbody>
</table>
<?php if($data["secteur"]["cnt"] > 0){ ?>
<div align="right"><input name="btnSupprimer" id="btnSupprimer" type="button" value="<?php echo _getText("main.btn.delete"); ?>" class="btn btn-blue"/></div>
<?php } ?>
<?php echo $paginationDisplay; ?>
When the page loads for the first time then the delete button works fine : the selected rows are deleted , and the list reappears accordingly to new database data. But later when I want to delete other rows then the alert does not show when I check some checkboxes and clicking the delete button !
So what is wrong in my approach ?
From what I am reading you are having problems with the row that are added from the database.
What could be the problem is when you execute this peace of code:
$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
When you call the $.click() function you add a event to all the existing DOM object that have a id of 'btnSupprimer', however this doesn't update if you add a new DOM object. So what you should do is call this function every time you add a new row. you would get something like this:
function rechercheSecteursEtProduits(pn){
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_user="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html);
$('#btnSupprimer').click(addClickHandler()); // this is the div element
}
function addClickHandler(){
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
}
I hope it helps
Try using on instead of click as below
$('#btnSupprimer').on("click","#liste_secteurs",function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
});
Use the dynamic jquery selector instead of the regular 'click' event
$('#liste_secteurs').on('click', '#btnSupprimer', function() {});
// $("container").on("event", "button", function() {});
As from Caveman's answer I made some updates :
function rechercheSecteursEtProduits(pn) {
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_usermer="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html);
$('#btnSupprimer').on('click',function(){
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
if (confirm("Do you want to remove these records ?")) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0);
}
}
});
}
And it works !