How To Set Checkbox Checked From Ajax Response In Datatable? - javascript

I have ajax response code here that dataCompetence has value 2,5. I Tried to find same id in column comp_id and then set checkbox checked. Here is my html code:
<table id="competence_list" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th width="1%"><input name="select_all_competence" class="case" id="example-select-all-competence" type="checkbox"></th>
<th hidden>ID</th>
<th width="10%">Aspect</th>
<th width="40%">Description</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
if ($this->competenceList) {
foreach ($this->competenceList as $data) {
?>
<tr>
<td><input type="checkbox" name="idcheckbox_competence" id="idcheckbox_competence" class="case"></td>
<td hidden id="comp_id"><?php echo $data['competence_id']; ?></td>
<td><?php echo $data['aspect']; ?></td>
<td><?php echo $data['descriptions']; ?></td>
</tr>
<?php
$i++;
}
}
?>
</tbody>
</table>
And this what i tried to set checkbox checked :
var dataCompetence = jsonData.dataCompetence;
if(jsonData.success){
$.gritter.removeAll();
$.each(dataCompetence.split(","), function(i,e){
$("#competence_list input[value='" + e + "']").prop("checked", true);
});
I don't know ow to find the same value and then set the checkbox checked, help me. Thanks

#Nike please try and follow these steps.......
Html
<div id="dvCheckBoxListControl"></div>
Jquery
<script>
$(document).ready(function () {
PopulateCheckBoxList();
})
function PopulateCheckBoxList() {
$.ajax({
type: "POST",
url: '#Url.Action("GetCheckBoxDetails", "Home")',
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
//error: AjaxFailed
});
}
function AjaxSucceeded(result) {
BindCheckBoxList(result);
}
function BindCheckBoxList(result) {
CreateCheckBoxList(result);
}
function CreateCheckBoxList(checkboxlistItems) {
var table = $('<table></table>');
var counter = 0;
$(checkboxlistItems).each(function () {
table.append($('<tr></tr>').append($('<td></td>').append($('<input>').attr({
type: 'checkbox', name: 'chklistitem', value: this.Value, id: 'chklistitem' + counter, checked:this.IsSelected
})).append(
$('<label>').attr({
for: 'chklistitem' + counter++
}).text(this.Name))));
});
$('#dvCheckBoxListControl').append(table);
}
Please create a model CheckBoxItem in your project like this..
Model
public class CheckBoxItem
{
public string Name { get; set; }
public string Value { get; set; }
public bool IsSelected { get; set; }
}
Controller
[HttpPost]
public ActionResult GetCheckBoxDetails()
{
List<CheckBoxItem> chkListAppointments = new List<CheckBoxItem>(){
new CheckBoxItem{ Value="1",Name="Jaipur", IsSelected=true},
new CheckBoxItem{ Value="2",Name="Ajmer",IsSelected=false},
new CheckBoxItem{ Value="3",Name="Sikar",IsSelected=true},
};
return Json(chkListAppointments, JsonRequestBehavior.AllowGet);
}

Related

How to delete row after i select the row and press the button

Screenshot
<?php
if(isset($_GET['View']) && $_GET['View']=="HistoryEntry"){
echo '
<h2>History Of Entries</h2>
<table id="table" class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Date In</th>
<th scope="col">Date Out</th>
<th scope="col">Rfid</th>
<th scope="col">Plate #</th>
</tr>
</thead>
<tbody>';
global $connection;
$query = "SELECT * FROM history_entries";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>
<th scope="row">'.$row['Entry_ID'].'</th>
<td>'.$row['Date_in'].'</td>
<td>'.$row['Date_out'].'</td>
<td>'.$row['Acc_rfid'].'</td>
<td>'.$row['Plate_num'].'</td>
</tr>';
}
echo ' </tbody>
</table>
<center>
<button>Delete</button>
</center>
<div class="line"></div>';
}
?>
?>
$("#table tr").click(function() {
$('.selected').removeClass('selected');
$(this).addClass("selected");
});
$("#Sample").click(function() {
var value = $(".selected th:first").html();
value = value || "No row Selected";
});
As you can see this my codes, i already know how to select the row and get the ID but cant pass the ID "value" to php in order to do the delete function in database. can i use here $.POST function here? or is it better to use GET function here but i think it wouldn't be secure.
This is how you can do it without get param :
1/ Your FRONT :
HTML (just an example)
<table>
<tr id="row_id">
<td>Data 1</td>
<td>Data 2</td>
...
</tr>
...
</table>
<button id="delete_row" type="button">Delete</button>
JS / jQuery
var current_row_id = "";
// You select the row
$("#table tr").click(function() {
$('.selected').removeClass('selected');
$(this).addClass("selected");
current_row_id = $(this).attr("id"); // Here you get the current row_id
});
// You delete the row
$("#delete_row").on("click", function() {
$.ajax({
type: "POST",
url: "delete.php",
data: {"id" : current_row_id }, // You send the current_row_id to your php file "delete.php" in post method
dataType: 'json', // you will get a JSON format as response
success: function(response){
// you do something if it works
},
error: function(x,e,t){
// if it doesn't works, check the error you get
console.log(x.responseText);
console.log(e);
console.log(t);
}
});
});
2/ Your BACK
PHP "delete.php" file
<?php
$id = $_POST['id']; // You get the 'current_row_id' value
// Now you do your DELETE request with this id :
$sql = "DELETE ... WHERE id = :id";
etc...
$result = array(); // You can prepare your response and send information about what you did
$result['row_deleted'] = $id;
$result['message'] = "The row with id = " . $id . " was deleted with success";
$result['type'] = "success";
//etc....
echo json_encode($result); // You send back a response in JSON format
3/ Back to the FRONT
Your ajax call, the success part :
success: function(response){
// You can display a success message for example using your response :
alert(response.message); // You will get 'The row with id = {the row id} was deleted with success' here for example
},
Is it what you are looking for?
here is a simple Ajax request
var data = {
rowId: 1
};
$.ajax({
type: "POST",// GET|POST
url: 'delete.php', // Where you want to send data like url or file
data: data, // this is what you want to send to server, in this case i send data with id = 1 to server
dataType: 'json' // here we say what data type we want "json"
success: function(response) {
alert(response);
}, // this is the callback were u will get response from your server
});
delete.php here is how u can handle this ajax
$rowId = htmlspecialchars($_POST['rowId']);
if ($rowId) {
global $connection;
$query = "DELETE FROM history_entries WHERE Entry_ID = " . $rowId;
$result = mysqli_query($connection, $query);
$response = array(
'success' => true
);
echo json_encode($response);
exit;
} else {
echo json_encode(array('success' => false));
exit;
}
Hope this will help you to understand how to use Ajax

CodeIgniter CSRF 403 error

I'm trying to solve this problem for a long time and stil have no clue to it.
I am trying to send and catch AJAX request within CodeIgniter framework.
PHP file with page tamplate:
<table id="jivoClients" class="display nowrap" cellspacing="0" width="100%">
<tbody>
<?php foreach($clients as $client): ?>
<td class="details-control" id="<?php echo $client["chat_id"]. ","
.$this->security->get_csrf_token_name(). ","
.$this->security->get_csrf_hash(); ?>"></td>
<th class="clientData"><?php echo str_replace(",", "<br>" , $client["visitor_info"]); ?></th>
<th class="clientData"><?php echo ($client['session_geoip_country']); ?></th>
<th class="clientData"><?php echo ($client['session_geoip_city']); ?></th>
<th class="clientData"><?php echo ($client['visitor_chats_count']); ?></th>
<th class="clientData"><?php echo ($client['agents_names']); ?></th>
<th class="clientData"><?php if(isset($client['messages']['0']['timestamp'])): ?>
<?php echo date('m/d/Y', $client['messages']['0']['timestamp']); ?>
<?php endif;?></th>
<th class="clientData"><?php if(isset($client['messages']['0']['timestamp'])): ?>
<?php echo date('H:i:s', $client['messages']['0']['timestamp']); ?>
<?php endif;?></th>
<th class="clientData"><?php if(isset($client['messages']['0']['Message'])): ?>
<?php echo ($client['messages']['0']['Message']); ?>
<?php endif;?></th>
<th class="clientData"><?php echo ($client['Manager_note']); ?></th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
In my js file code looks like:
var id = $(this).attr('id');
var messageData = id.split(",");
var token = "" + messageData[1];
var post_data = {
'id' : messageData[0],
'csrf_crm' : messageData[2]
}
$.ajax({
type:'POST',
data: {
func : 'getNewLocations',
'id' : messageData[0],
'csrf_crm' : messageData[2]
},
url:'application/controllers/AjaxController.php',
success: function(result, statut) {
if (result == 'add') {
//do something
}
else if (result == 'remove') {
//do something
}
}
});
And I constantly get 403 error. As I already read on forum, it means that my CSRF token is not correct. But it seems that I get it normally (checked in debugger).
However this does not solve the problem.
Thanks in advance.
You need to do echo to assign value of php variable. Also wrap token in ''
var token = '<?php echo $this->security->get_csrf_hash() ?>'; //<----- do echo here
var id = $(this).attr('id');
$.ajax({
type:'POST',
data: {
func : 'getNewLocations',
'id' : id,
'csrf_crm' : token
},
url:'application/controllers/AjaxController.php',
success: function(result, statut) {
if (result == 'add') {
//do something
}
else if (result == 'remove') {
//do something
}
}
});
Get the csrf token value like this:
var token = $('[name="csrf_token"]').val();
Finally I solved this problem.
It appered, that I was using incorrect route in js file.
The correct sequence of actions looks like this:
1) add new line in file routes.php:
$route['jivosite/user'] = 'jivosite/user';
2) add code in js file:
post_data = JSON.stringify(post_data);
post_data = JSON.stringify(post_data);
var url = baseurl + "jivosite/user"
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.addEventListener("readystatechange", function () {
if (xhr.readyState == 4 && xhr.status === 200) {
console.log(xhr.response);
}
});
xhr.addEventListener("error", function (err) {
console.log(err);
});
xhr.send(post_data ? JSON.stringify(post_data) : null);
3) check config.php file.
$config['cookie_secure'] = FALSE; should be like this
and $config['csrf_exclude_uris'] = array('jivosite/user'); should include my route
4) create file Jivosite.php in controllers folder with contents:
class Jivosite extends CI_Controller
{
public function user()
{
$id=$this->input->post('id');
echo $id;
}
}
And it worked for me.
Thanks for all answers.

How do i show my table?

This is my index.php view were my table is placed
<table class="striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Address</th>
<th>Created at</th>
</tr>
</thead>
<tbody id="showdata">
<!--<tr>
<td>1</td>
<td>Alvin</td>
<td>Eclair</td>
<td>$0.87</td>
<td>
Edit
Delete
</td>
</tr>-->
</tbody>
</table>
This my ajax script placed on index.php
function showAllEmployee() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url(); ?>index.php/Employee/showAllEmployee',
async: false,
dataType: 'json',
success: function(data) {
//console.log(data);
var html = '';
var i;
for (i=0; i<data.length; i++) {
html += '<tr>'+
'<td>'+data[i].emp_id+'</td>'+
'<td>'+data[i].name+'</td>'+
'<td>'+data[i].address+'</td>'+
'<td>'+data[i].created_at+'</td>'+
'<td>'+
'Edit'+
'Delete'+
'</td>'+
'</tr>';
}
$('#showdata').html(html);
},
error: function() {
alert('Could not get data from database');
}
});
}
This is what i have on my employee controller
public function showAllEmployee()
{
$result = $this->em->showAllEmployee();
echo json_encode($result);
}
This is my model
public function showAllEmployee()
{
$this->db->order_by('created_at', 'desc');
$query = $this->db->get('tbl_employees');
if($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Whenever i refresh the page the data wont display instead i run into an error could not get the data from the database which is the condition i set on my ajax script what could be wrong pls help
set header as JSON type in the controller
change your controller to
public function showAllEmployee(){
$result = $this->em->showAllEmployee();
$this->output
->set_content_type('application/json')
->set_output(json_encode($result));
}

Excel-like Updating a table without a button in PHP and AJAX

I need to update a row of a table. So when I click on a cell, I want it to be transformed into text box, so I used this:
<td contenteditable></td>
And then, when the content of a <td> is changed, I need to send it through AJAX to update it in the server without clicking on a button, so it will use the .change(function()).
I tried to get the content changed into a variable:
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid = '<?php echo $row['id'] ?>';
var name = $("#emp_name").val();
var position = $("#position").val();
var salary = $("#salary").val();
$.ajax
({
url: 'update.php',
type: 'POST',
data: {dataId: rowid, data1: name, data2: position, data3: salary},//Now we can use $_POST[data1];
dataType: "text",
success:function(data)
{
if(data=="success")
{
//alert("Data added");
$("#before_tr").before("<tr><td>"+emp+"</td><td>"+pos+"</td><td>"+sal+"</td></tr>");
$("#emp_name").val("");
$("#position").val("");
$("#salary").val("");
}
},
error:function(data)
{
if(data!="success")
{
alert("data not added");
}
}
});
});
The problem is how to know which row is changed to send it via AJAX ? I am not getting any errors even when data not updated.
Here is the update.php code:
try
{
$rowid = $_POST['dataId'];
$emp_name = $_POST['data1'];
$pos = $_POST['data2'];
$sal = $_POST['data3'];
$upd = "UPDATE emp SET name = :emp_name, position = :pos, sal = :sal WHERE id = :rowid";
$updStmt = $conn->prepare($upd);
$updStmt->bindValue(":rowid", $rowid);
$updStmt->bindValue(":emp_name", $emp_name);
$updStmt->bindValue(":pos", $pos);
$updStmt->bindValue(":sal", $sal);
$updStmt->execute();
echo "success";
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
HTML:
<tbody>
<?php
$sql = "SELECT * FROM employee";
$stmt=$conn->prepare($sql);
$stmt->execute();
$res=$stmt->fetchAll();
foreach($res as $row){
?>
<tr id=""<?php echo $row['id'] ?>"">
<td contenteditable><?php echo $row['emp_name'] ?></td>
<td contenteditable><?php echo $row['position'] ?></td>
<td contenteditable><?php echo $row['salary'] ?></td>
</tr>
<?php } ?>
When loading your data with PHP you need to keep the row id in your html:
<tr id="<?php echo $yourList["id"]; ?>">
<td contenteditable></td>
</tr>
Then in your javascript you can catch it using the parent() jquery function
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid =$(this).parent().attr("id");
......
UPDATE
Check this example, I have added listeners to detect contenteditable td changes, I think you shall add it too , refer to this contenteditable change events for defining proper change events on contenteditable fields.
Explanation:
The contenteditable does not trigger change events, this work around is used to detect the focus event of the td using jquery on method and event delegation. The original content is saved in the td jquery data object $this.data('before', $this.html()); . Then when the user leaves the field or triggers any of the events 'blur keyup paste input', the current content is compared to the content in the data object, if it differs, the change event of the td is triggered.
$(document).ready(function(){
$('table').on('focus', '[contenteditable]', function() {
var $this = $(this);
$this.data('before', $this.html());
return $this;
}).on('blur keyup paste input', '[contenteditable]', function() {
var $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
return $this;
});
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid = $(this).parent().attr("id");
$("#res").html(rowid);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" width="500px">
<tr id="1222">
<td contenteditable></td>
</tr>
<tr id="55555">
<td contenteditable></td>
</tr>
</table>
Row Id : <span id="res"></span>
<tr row_id="<?php echo $row['id'] ?>"> ></tr>
In Your Ajax
var rowid = $(this).attr('row_id');

Table is not refreshed asynchronously AJAX,JQuery and PHP

I am trying to add a new row to the existing table using Ajax, PHP and Jquery.
Ajax call is successful (tested it by placing alerts). But it displays the new row only if I refresh the entire page. I want the row to be added to the table with out refreshing the entire page, but just with a table refresh on the fly.
example : As I press Add button on the table, it should add a new row to the table on the fly.
hotTopics_focusAreas_data.php file :
<?php
$SQL = "select * from hottopics order by id desc limit 1";
while($row = mysql_fetch_array($SQL,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
Javascript file :
$("document").ready(function() {
hotAddClicked();
});
function hotAddClicked(){
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table").append(data);
}
});
});
}
Table definition:
<table class="table" id="hottopics_table">
<thead>
<tr>
<th>Title</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$SQL = "select * from hottopics;";
$result_update = mysql_query($SQL) or die("Couldn't execute query.".mysql_error());
while($row = mysql_fetch_array($result_update,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
</tbody>
</table>
$(document).ready(function() {
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table tbody").append(data);
}
});
});
});
Check this jQuery script and check if it works properly.

Categories

Resources