Javascript in Codeigniter - javascript

I have the following code to add, edit and delete user. Add function works fine but edit and delete functions are not working. I'm not sure where it goes wrong.
application/view/userlist.php
<script type="text/javascript">
var oTable;
$(document).ready(function()
{
oTable = $('#userListTable').dataTable( {
"iDisplayLength": 25,
"aLengthMenu": [5,10,25,50,100],
"aoColumns": [ {
"bSortable": false },
null,
null,
null,
null,
null,
null,
null,
null, {
"bSortable": false } ]
});
oTable.fnSort( [ [1,'asc'] ] );
});
function removeUser()
{
var ids = '';
$("input:checked", oTable.fnGetNodes()).each(function(){
if (ids == '') {
ids += $(this).val();
}else{
ids += ','+$(this).val();
}
});
var url = "<?php echo base_url(); ?>Admin/userRemove/";
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="ids" value="' + ids + '" />' +
'</form>');
console.log(form);
$('body').append(form);
if (ids != '') {
form.submit();
}else{
alert('Select user to remove');
}
}
</script>
//some codes here
<button type="button" data-hover="tooltip" onclick="removeUser()" title="Delete Selected" class="btn btn-default">
<i class="fa fa-eraser"></i>
</button>
<button type="button" data-hover="tooltip" title="Add New User" class="btn btn-default">
<div class="panel-header" data-toggle="modal" data-target="#myModal">
<i class="fa fa-user-plus fa-1x"></i>
</div>
</button>
// #myModal codes here
<script type="text/javascript">
$(document).ready(function(){
$('.edit-row').live('click',function(){
var me = $(this);
var editModal = $('#myModalEdit');
editModal.find('#userID').val(me.attr('data-userID'));
editModal.find('#userName').val(me.attr('data-userName'));
editModal.find('#userFullName').val(me.attr('data-userFullName'));
editModal.find('#userPass').val(me.attr('data-userPass'));
editModal.find('#userEmail').val(me.attr('data-userEmail'));
$('#myModalEdit').modal('show');
});
});
</script>
//#myModalEdit codes here
<table id="userListTable" class="table table-hover table-striped table-bordered" >
<thead>
<tr>
<th><center><strong>#</strong></center></th>
<th><h4><strong>USER ID</strong></h4></th>
<th><h4><strong>FULL NAME</strong></h4></th>
<th><h4><strong>USERNAME</strong></h4></th>
<th><h4><strong>EMAIL</strong></h4></th>
</tr>
</thead>
<tbody>
<?php
if(!empty($data_user)):
foreach($data_user as $row)
{
echo '<tr>
<td class="text-center">
<input type="checkbox" name="selectAction" value="'.$row->userID.'" unchecked>
</td>';
echo '<td>'.$row->userID.'</td>';
?>
<td><a class="edit-row" href="javascript:"
data-userID="<?php echo $row->userID; ?>"
data-userFullName="<?php echo $row->userFullName; ?>"
data-userName="<?php echo $row->userName; ?>"
data-userEmail="<?php echo $row->userEmail; ?>"
>
<?php echo $row->userFullName; ?>
</a>
</td>
<?php
echo '<td>'.$row->userName.'</td>';
echo '<td>'.$row->userEmail.'</td>';
echo '</tr>';
}
endif;
?>
</tbody>
</thead>
</table>
// other codes
application/controllers/Admin.php
public function userRemove() {
$ids = $this->input->post('ids');
if (!empty($ids)) {
$this->db->where('userID IN (' . $this->input->post('ids') . ')')
->
delete('user_tbl', $data);
}
redirect('userlist', 'refresh');
}
Edit and delete functions seems not working..

Related

Getting Data from row which button is clicked

I have the following ajax that needs to pass the userID to a PHP script.
document.getElementById("delete").addEventListener("click", function(){
if (confirm("Are you sure you want to delete this user's account?")) {
$.ajax({
url: 'deleteUser.php?id='+<?php echo $userID ?>,
success: function(data) {
toastr.danger("User successfully deleted!");
}
});
} else {
}
});
I'm unsure how to actually get the row data from the button used since they're posted in the TD of each row as it goes through each record in the set. How would one accomplish this?
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Email</th>
<th scope="col">Username</th>
<th scope="col">Account Type</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<?php
$query = $pdo->query("SELECT * FROM accounts WHERE company ='".$res['company']."' ")->fetchall();
foreach($query as $row){
echo ' <tr>';
echo ' <td>'.$row['fname'].'</td>' ;
echo ' <td>'.$row['lname'].'</td>' ;
echo ' <td>'.$row['email'].'</td>' ;
echo ' <td>'.$row['account_name'].'</td>' ;
echo ' <td>'.$row['user_type'].'</td>' ;
echo ' <td><button id="delete" type="button" class="btn btn-danger"><i class="far fa-trash-alt"></i></button>';
echo ' <button id="edit" type="button" class="btn btn-info"><i class="fas fa-user-edit"></i></button> </td>';
echo ' </tr>';
}
?>
</tbody>
</table>
You can do it this way:
php:
foreach($query as $row){
echo ' <tr>';
echo ' <td>'.$row['fname'].'</td>' ;
echo ' <td>'.$row['lname'].'</td>' ;
echo ' <td>'.$row['email'].'</td>' ;
echo ' <td>'.$row['account_name'].'</td>' ;
echo ' <td>'.$row['user_type'].'</td>' ;
echo ' <td><button data-id="' . $row['id'] . '" type="button" class="btn btn-danger delete"><i class="far fa-trash-alt"></i></button>';
echo ' <button type="button" class="btn btn-info edit"><i class="fas fa-user-edit"></i></button> </td>';
echo ' </tr>';
}
Jquery:
$("button.delete").each(function(){
$(this).on('click', function(e){
if (confirm("Are you sure you want to delete this user's account?")) {
$.ajax({
url: 'deleteUser.php?id='+$(this).data('id'),
success: function(data) {
toastr.danger("User successfully deleted!");
}
});
} else {
//do something else
}
});
});
HTML 4.01 specification says ID must be document-wide unique.
HTML 5 specification says the same thing but in other words. It says that ID must be unique in its home subtree, which is basically the document if we read the definition of it.
I'd fix that first: <button id="delete" needs to be unique
Next - I'd add an onClick to your delete button so you have <button onclick="deleteUser(2);"
Then, I'd rewrite your listener registration to just be a function:
function deleteUser(id){
if (confirm("Are you sure you want to delete this user's account?")) {
$.ajax({
url: 'deleteUser.php?id='+<?php echo $userID ?>,
success: function(data) {
toastr.danger("User successfully deleted!");
}
}

I am getting same value of every button

i have fetch the data from database every thing work fine but problem is when i submit ajax request to test.php i got same value of every button
I am very week in Ajax and Java so please help me ,i am confuse how to get value of every button separately and submit to test.php file
<tbody>
<?php
$letter = mysqli_query($con,"SELECT * FROM letters order by id DESC");
if (mysqli_num_rows($letter) > 0) {
while ($rows_letter=mysqli_fetch_array($letter)) {
$id = $rows_letter['id'];
$subject = $rows_letter['subject'];
$status = $rows_letter['status'];
?>
<tr>
<th class="text-center" scope="row">1</th>
<td class="text-center"><?php echo $subject ;?></td>
<td class="text-center">
<?php
if ($status == 1) {
echo '<mark style="background-color: #5cb85c; color:white;"> Successfully Sent </mark>';
} else {
echo '<mark style="background-color:#f0ad4e; color:white;"> Not Sent Yet </mark>';
}
?>
</td>
<td>
<button type="button" class="btn btn-info btn-sm btn-block">
<span class="fa fa-pencil-square-o"></span> Edit</button>
</td>
<td>
<button type="button" class="btn btn-danger btn-sm btn-block">
<span class="fa fa-trash-o"></span> Move To Trash</button>
</td>
<td>
<button type="button" onclick="startsend();" id="id" value="<?php echo $id;?>"class="btn btn-success btn-sm btn-block">
<span class="fa fa-paper-plane-o"></span> Send To All</button>
</td>
</tr>
<?php
}
}
?>
</tbody>
<script type='text/javascript'>
//AJAX function
function startsend() {
var id = $('#id').val();
$.ajax({
type: "POST",
url: "test.php",
data:{ id: id
},
success: function(msg){
alert( "Button Id is " + msg );
}
});
}
</script>
and this is my test.php file
<?php
$id = $_POST['id']; echo $id;
//// rest of process according to id
?>
Try this, pass the id as param to ajax
Html:
<td><button type="button" onclick="startsend(<?php echo $id;?>);"
id="id" value="<?php echo $id;?>"class="btn btn-success btn-sm btn-block">
<span class="fa fa-paper-plane-o"></span> Send To All</button></td>
Ajax:
function startsend(id) {
$.ajax({
type: "POST",
url: "test.php",
data:{ id: id },
success: function(msg){
alert( "Button Id is " + msg );
}
});
}

Ajax inside Datatables Custom Button Action

I want to store datatables data inside an array or json format and use it to pass to php for FPDF use. In my datatable I created a custom button named "PDF", when the button is click I want to store the data and pass it into php via post. I have this code, but it wont work if I put ajax inside the action function of the custom button I made. It doesnt go to the url I declared. Here's the code:
EDITED
<script>
$(document).ready(function() {
var table = $('#stud_list').DataTable({
dom: 'Blfrtip',
columnDefs: [{
targets: 1,
className: 'noVis'
}],
buttons: [{
extend: 'excelHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'csvHtml5',
exportOptions: {
columns: ':visible'
}
},
{
text: 'PDF',
exportOptions: {
columns: ':visible'
},
action: function(e, dt, node, config) {
$.ajax({
url: 'pdfViewStudent.php',
type: 'post',
data: table.row().data().toArray(),
dataType: 'json',
success: function(returnedData) {
console.log(returnedData);
}
});
}
},
'colvis'
],
columnDefs: [{
targets: -1,
visible: false
}],
initComplete: function() {
this.api().columns([4, 5, 6]).every(function() {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function() {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function(d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
});
</script>
I edited the code, the error was gone but nothing happens also.
ADDED HTML CODE:
<table id="stud_list" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Last Name</th>
<th>First Name</th>
<th>Initials</th>
<th>Grade</th>
<th>Section</th>
<th>Gender</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$result = mysqli_query($connect, "SELECT * FROM tbl_student") or die(mysqli_error());
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
?>
<tr>
<td>
<?php echo $row['student_id']; ?>
</td>
<td>
<?php echo $row['last_name']; ?>
</td>
<td>
<?php echo $row['first_name']; ?>
</td>
<td>
<?php echo $row['Initials']; ?>
</td>
<td>
<?php echo $row['gradeLevel_id']; ?>
</td>
<td>
<?php echo $row['section_id']; ?>
</td>
<td>
<?php echo $row['gender']; ?>
</td>
<td>
<a class="btn btn-success btn-xs" href="studentProfile.php?studId=<?php echo $row['student_id']; ?>"><i class="fa fa-eye fa-1x"></i></a>
<button type="button" class="btn btn-info btn-xs" data-toggle="modal" data-target="#editStudent" data-studaydi="<?php echo $row['student_id']; ?>" data-cardaydi="<?php echo $row['card_id']; ?>" data-seksyon="<?php echo $row['section_id']; ?>" data-gardyan="<?php echo $row['Parents_No']; ?>" data-location="<?php echo $row['address']; ?>" data-ln="<?php echo $row['last_name']; ?>" data-fn="<?php echo $row['first_name']; ?>" data-mn="<?php echo $row['Initials']; ?>" data-gn="<?php echo $row['gender']; ?>" data-cy="<?php echo $row['cyear']; ?>" data-gr="<?php echo $row['gradeLevel_id']; ?>"><i class="fa fa-edit fa-1x"></i></button>
<a onclick="javascript: return confirm('DO YOU REALLY WANT TO DELETE THIS STUDENT?');" href="removeStudent.php?id=<?php echo $row['student_id']; ?>" class="btn btn-danger btn-xs"><i class="fa fa-remove fa-1x"></i></a>
</td>
<?php } ?>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>

Jquery 2.1 - On click is stacking calls

I have a strange bug with on click event. Every time I click on button it is adding one more post call. If I click update button once it will do one post call, if I click it again (for the second time) it will make two post calls and so one. The code it self is working, but this bug is a bit annoying. Does anyone have idea what is going one?
var
editCutomerType = $('a[role=editCutomerType]'),
deleteCutomerType = $('a[role=deleteCutomerType]');
editCutomerType.on('click', function(e) {
var
$this = $(this),
parentContainer = $this.closest('.parent'),
nameContainer = parentContainer.find('.name'),
update = $this.next('a'),
cancel = update.next('a'),
oldName = nameContainer.text()
i = 0;
$this.hide();
update.removeClass('hidden');
cancel.removeClass('hidden');
nameContainer.empty().append('<input type=text name=name value="' + oldName + '">');
update.on('click', function(e) {
var
url = $(this).attr('href'),
newName = parentContainer.find('input').val(),
data = 'name=' + newName;
$.post(url, data, function(data, textStatus, xhr) {
nameContainer.empty().text(newName);
$this.show();
update.addClass('hidden');
cancel.addClass('hidden');
});
return false;
});
cancel.on('click', function(e) {
nameContainer.empty().text(oldName);
$this.show();
update.addClass('hidden');
cancel.addClass('hidden');
return false;
});
i++;
console.log(i);
return false;
});
HTML code:
<div class="col-md-7">
<div class="panel panel-dark panel-light-green">
<div class="panel-heading">
<span class="panel-title"><i class="panel-title-icon fa fa-smile-o"></i>Customer Types</span>
</div> <!-- / .panel-heading -->
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th></th>
</tr>
</thead>
<tbody class="valign-middle">
<?php
$i = 1;
foreach ($customerTypes as $ct): ?>
<tr class="parent">
<td><?php echo $i ?></td>
<td class="name"><?php echo $ct['name'] ?></td>
<td>
<a role="editCutomerType" class="btn btn-primary btn-xs">Edit</a>
<a class="btn btn-primary btn-xs hidden" href="<?php echo base_url("customerTypes/save/{$ct['id']}") ?>">Update</a>
<a role="cancel" class="btn btn-warning btn-xs hidden">Cancel</a>
<a role="deleteCutomerType" class="btn btn-danger btn-xs" href="<?php echo base_url("customerTypes/delete/{$ct['id']}") ?>">Delete</a>
</td>
<td></td>
</tr>
<?php $i++; endforeach ?>
</tbody>
</table>
</div> <!-- / .panel -->
</div>
Give your update link a role like your other buttons:
foreach ($customerTypes as $ct): ?>
<tr class="parent">
<td><?php echo $i ?></td>
<td class="name"><?php echo $ct['name'] ?></td>
<td>
<a role="editCutomerType" class="btn btn-primary btn-xs">Edit</a>
<a role="update" class="btn btn-primary btn-xs hidden" href="<?php echo base_url("customerTypes/save/{$ct['id']}") ?>">Update</a>
<a role="cancel" class="btn btn-warning btn-xs hidden">Cancel</a>
<a role="deleteCutomerType" class="btn btn-danger btn-xs" href="<?php echo base_url("customerTypes/delete/{$ct['id']}") ?>">Delete</a>
</td>
<td></td>
</tr>
<?php $i++; endforeach ?>
Then you can bind handlers for update and cancel outside the editCutomerType handler:
$("a[role=update]").on('click', function(e) {
var
$this = $(this),
cancel = $this.next('a'),
edit = $this.prev('a'),
url = $this.attr('href'),
newName = $this.closest('.parent').find('input').val(),
nameContainer = parentContainer.find('.name'),
data = 'name=' + newName;
$.post(url, data, function(data, textStatus, xhr) {
nameContainer.empty().text(newName);
edit.show();
$this.addClass('hidden');
cancel.addClass('hidden');
});
return false;
});
You can do the cancel button similarly.
To stop the handler from being executed more than once, add stopImmediatePropagation() to the function.
update.on('click', function(e) {
var
url = $(this).attr('href'),
newName = parentContainer.find('input').val(),
data = 'name=' + newName;
$.post(url, data, function(data, textStatus, xhr) {
nameContainer.empty().text(newName);
$this.show();
update.addClass('hidden');
cancel.addClass('hidden');
});
return false;
e.stopImmediatePropagation();
});
To remove the old handler, you can call update.off('click').on('click', ...
Do the same for the cancel event.
Sent from phone, so sorry for not being verbose.

Set hidden field value by Javascript

How can I pass USER_ID of the tag < a > for a Javascript function Javascript that set a hidden field?
I tried the Javascript function showConfirm(), but the hidden field isn't being filled. It stays null... I think the onClick attribute, of the field deleteid, is wrote wrong.
I want fill this field by javascript. How can I?
The message of error says
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '' at line 1
probably because the hidden field "id_action" isn't receiving datas of the function.
Whatever, the main problem is set the function showConfirm by paramters 'show', $row['id'] for the hidden field id_action.
<script>
function showConfirm (action, delID) {
if (action == 'show') {
document.confirm.id_action.value = delID;
}
}
</script>
<tbody>
<?php
if (!empty($_POST)) {
if (isset($_POST['id_action'])) {
$del_id = $_POST['id_action'];
$delUser = new User;
$delUser->deletarUsuario($del_id);
unset($delUser);
}
}
$listUser = new User;
$result = $listUser->listarUsers();
if (is_array($result)) {
foreach ($result as $row) {
echo "
<tr>
<td align='right'>" . $row['id'] . "</td>
<td>". $row['name'] . " ".$row['sobrename']."</td>
<td>" . $row['email'] . "</td>
<td>" . $row['login'] . "</td>
<td>
<a data-toggle='modal' id='deleteid' data-target='#modal_delUser' onclick=\"showConfirm('show'," . $row['id'] . ")\">
Remove
</a>
</td>
</tr>";
}
}
unset($listUser);
?>
</tbody>
<!-- Button trigger modal -->
<div class='modal fade' id='modal_delUser' tabindex='-1' role='dialog' aria-labelledby='modal_delUserLabel' aria-hidden='true'>
<div class='modal-dialog'>
<div class='modal-content panel-danger'>
<div class='modal-header panel-heading'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h4 class='modal-title' id='modal_delUserLabel'>The user will be deleted</h4>
</div>
<div class='modal-body'>
Are you sure continue?
</div>
<div class="modal-footer">
<form role="form" id="confirm" action="users.php" method="post">
<input type="hidden" name="id_action">
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
<button type="submit" class="btn btn-danger">Yes</button>
</form>
</div>
</div>
</div>
</div>
Here the SQL that I am generating from the query
public function deletarUsuario($id) {
$del_id = $this->db->real_escape_string(trim($id));
if ($update = $this->db->query("DELETE FROM usuario WHERE id = $del_id")) {
if ($this->db->affected_rows) {
echo "<div><p>Deleted user!</p></div>";
}
else {
echo "<div><p>Failed to delete user.</p></div>";
}
}
else {
echo "<div><p>". $this->db->error."</p></div>";
echo "<script>$('#modal_erroBD').modal('show');</script>";
}
}
Do it in php by using $id_action = $_POST["id_action"]
Check if you are passing the id at this stage:
change
if (isset($_POST['id_action'])) {
$del_id = $_POST['id_action'];
$delUser = new User;
$delUser->deletarUsuario($del_id);
unset($delUser);
}
to
if (isset($_POST['id_action'])) {
$del_id = $_POST['id_action'];
echo $del_id;
}

Categories

Resources