Deleting users from the database using AJAX and Codeigniter - php

I'm trying to delete users from the database using AJAX and Code Igniter. When I click the delete link, the user gets deleted but the page gets redirected and success message is displayed. AJAX does not seem to work in my code.
Here's HTML:
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Username</th>
<th>Password</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $u){?>
<tr>
<td><?php echo $u['id']; ?></td>
<td><?php echo $u['firstname']; ?></td>
<td><?php echo $u['lastname']; ?></td>
<td><?php echo $u['email']; ?></td>
<td><?php echo $u['username']; ?></td>
<td><?php echo $u['password']; ?></td>
<td>
<a href="#" >Edit</a> |
<?php $id=$u['id'];?>
Delete
</td>
<?php }?>
</tr>
</tbody>
</table>
and here's AJAX:
$(document).ready(function(){
$(".delete").click(function(){
alert("Delete?");
var href = $(this).attr("href");
var btn = this;
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
})
});
and lastly the controller function to delete the user in Codeigniter
public function delete($id)//for deleting the user
{
$this->load->model('Users_m');
$delete=$this->Users_m->delete_user($id);
if($delete)
{
echo "Success";
}
else
{
echo "Error";
}
}
Where am I making the mistake?

Just to expand on the correct answers already given here.
Basically, your JS code should look like:
$(document).ready(function(){
$(".delete").click(function(event){
alert("Delete?");
var href = $(this).attr("href")
var btn = this;
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
event.preventDefault();
})
});
The event.preventDefault() part is important here. As it prevents the browser from taking the default action it takes if you click on an element.
In the case of a link, that would be redirecting you to the url that is defined in the href parameter. Which is what you see happening.
Your manually defined event is always triggered first, so the ajax request is indeed started, but right after that your event handler, the browser starts handling the default action, breaks off the ajax request, and navigates to the clicked link.

Make sure you are setting the correct object to the 'btn' var:
var btn = $(this);
See if this is the issue!
by the way you are missing a semicolon in:
var href = $(this).attr("href")

the default action of the event should not be triggered.
For this use event.preventDefault()

$(".delete").click(function(e){
e.preventDefault();
...

You are not preventing the default behavior of the anchor so it will redirect you and make the ajax request
$(document).ready(function(){
$(".delete").click(function(e){
alert("Delete?");
e.preventDefault();
var href = $(this).attr("href");
var btn = this;
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
})
});
I hope this can help :)

First you change the href attribute another attribute like name or value because first time it loads and another time it stores the value in href and after that write this for refreshing page
window.reload('true');
this will surely help you

Related

I want to grab the UID of clicked row using ajax from foreach loop php but getting all UID

I'm trying to get the UID from an anchor tag which is the value of ID attribute of the anchor tag from a foreach loop PHP in ajax. But it only work once a time, when I click the anchor tag again then all the UIDs are grabbed in the ajax!
When I click on anchor tag then 1st I'm displaying a bootstrap 4 modal and in modal a textarea tag is present with a button and when I click button then I've to send uid and message again to the action.php page
This is my action.php code
if(isset($_POST['action']) && $_POST['action'] == 'fetchAllFeedback'){
$feedback = $admin->fetchFeedback();
$output = '';
if($feedback){
$output .= '<table class="table table-striped table-bordered text-center">
<thead>
<tr>
<th>FID</th>
<th>UID</th>
<th>User Name</th>
<th>User E-Mail</th>
<th>Subject</th>
<th>Feedback</th>
<th>Sent On</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
foreach ($feedback as $row) {
$output .= '<tr>
<td>'.$row['id'].'</td>
<td>'.$row['uid'].'</td>
<td>'.$row['name'].'</td>
<td>'.$row['email'].'</td>
<td>'.$row['subject'].'</td>
<td>'.$row['feedback'].'</td>
<td>'.$row['created_at'].'</td>
<td>
<i class="fas fa-reply fa-lg"></i>
</td>
</tr>';
}
$output .= '</tbody>
</table>';
echo $output;
}
else{
echo '<h3 class="text-center text-secondary">:( No any feedback written yet!</h3>';
}
}
This is feedback.php ajax code
$("body").on("click", ".feedbackReplyIcon", function(e){
let uid = $(this).attr('id');
$("#feedback-reply-btn").click(function(e){
if($("#feedback-reply-form")[0].checkValidity()){
let message = $("#message").val();
e.preventDefault();
$("#feedback-reply-btn").val('Please Wait...');
$.ajax({
url: 'assets/php/admin-action.php',
method: 'post',
data: {uid:uid,message:message},
success:function(response){
console.log(response);
$("#feedback-reply-btn").val('Send Reply');
$("#showReplyModal").modal('hide');
$("#feedback-reply-form")[0].reset();
}
});
}
});
});
Here is what I believe happens: Since you declare a click method inside another click method, the uid variable turns empty after the first use. It's generally a bad practice to stack events like this inside one another. Try changing your javascript to this:
var uid;
$("body").on("click", ".feedbackReplyIcon", function(e){
uid = $(this).attr('id');
});
$("#feedback-reply-btn").click(function(e){
if($("#feedback-reply-form")[0].checkValidity()){
let message = $("#message").val();
e.preventDefault();
$("#feedback-reply-btn").val('Please Wait...');
$.ajax({
url: 'assets/php/admin-action.php',
method: 'post',
data: {uid:uid,message:message},
success:function(response){
console.log(response);
$("#feedback-reply-btn").val('Send Reply');
$("#showReplyModal").modal('hide');
$("#feedback-reply-form")[0].reset();
}
});
}
});
This might still be less than optimal, I'm a bit unclear on how your elements are laid out, and I can't really test it out. Let me know on what happens - if it still doesn't work, try dumping out the variables in admin-action.php , and see what's in there.

tablesorter JS not working when content generated via ajax

I'm not looking to add to / append an existing table. My table is empty until results are returned via AJAX. I'm trying to sort my tables data via the javascript plugin, tablesorter.js.
I have sorted my table so It's split between header and body. I can't seem to get the table rows to change though
My Code for the AJAX is;
<script>
$(document).ready(function()
{
$("#results").tablesorter();
}
);
</script>
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#to_date").datepicker();
});
var to_date = $('#to_date').val();
$( "#genre" ).val();
{
var value = $(this).val();
$( "#price" ).val();
{
var value = $(this).val();
$('#filter').click(function(){
var to_date = $('#to_date').val();
var request = $("#genre").val();
var request1 = $("#price").val();
var data = 'to_date'+'request'+'request1';
if(to_date != '' )
{
$.ajax({
url:"filter.php",
method:"POST",
data: { to_date:to_date, request:request,request1:request1 },
success:function(data)
{
$('#results').html(data);
$('#results').trigger("update");
}
});
}
else
{
alert("Please Select Date");
}
});
};
};
});
</script>
and my code for the html / PHP is;
<table id="results" class="tablesorter">
<thead>
<tr>
<th>Event</th>
<th>Venue</th>
<th>Genre</th>
<th>Date</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["event_name"]; ?></td>
<td><?php echo $row["venue_name"]; ?></td>
<td><?php echo $row["genre"]; ?></td>
<td><?php echo $row["event_date"]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
you never actually called to the plugin:
$("results").tablesorter()
Everytime you get your data updated you should make a all to the tablesorters update trigger so it gets its references updated.
success:function(data)
{
$('#results').html(data);
$('#results').trigger("update");
}
that should do the trick

delete data using ajax and codeigniter

I have problem in deleting data using ajax I tried first to test if I click the button to make alert action so it not work.
this is my controller code
public function indexajax()
{
$this->load->model("usersmodel");
$data["allu"]=$this->usersmodel->ShowAllUsers("users");
$data['pagetitle']=" -->All Users Using Ajax<--";
$this->load->view("template/admin/header",$data);
$this->load->view("users/allusersusingajax");
$this->load->view("template/admin/footer");
}
public function get_all_users()
{
if($this->input->post("action")=='FetchAllUserUingAjax1'){
$this->load->model("usersmodel");
$x= $data["allu"]=$this->usersmodel->ShowAllUsers("users");
foreach ($x as $a):
echo'<tr>
<td>'.$a->id.'</td>
<td>'.$a->username.'</td>
<td><button class="deletenew" id="'.$a->id.'">delete</button></td>
</tr>';
endforeach;
}
public function deleteusers()
{
$id=$this->input->post("id");
$this->load->model("usersmodel");
$this->usersmodel->deleteusers($id);
}
this is my model code for deleting
public function deleteusers($id)
{
$this->db->where('id',$id);
if($this->db->delete("users")){
return true;
}else{
return false;
}
}
/**************this is view page *****/
<div class="userdataajax table-responsive">
<table class=" table table-responsive table-bordered">
<tr>
<th>#</th>
<th>name</th>
<th>image</th>
<th> full name</th>
<th>email</th>
<th>usertype</th>
<th>status</th>
<th>reg date</th>
<th>reg time</th>
<th>delete</th>
<th>edit</th>
<th>Activate</th>
<th>disactivate</th>
</tr>
</table>
</div>
<script>
$(document).ready(function () {
FetchAllUserUingAjax();
function FetchAllUserUingAjax() {
$.ajax({
url:'<?php echo base_url()?>Users/get_all_users',
method:"post",
success:function (data) {
$(".userdataajax table").append(data);
}
})
var action="FetchAllUserUingAjax1";
$.ajax({
url:"<?php echo base_url()?>Users/get_all_users",
method:"post",
data:{action:action},
success:function (data) {
$(".userdataajax table tr").not("table
tr:first").remove();
$(".userdataajax table").append(data);
Table();
}
})
};
$(".deletenew").on("click",function () {
alert("engex");//this alert not working
var id=$(this).attr('id');
$.ajax({
url:"<?php echo base_url()?>Users/deleteusers",
method:"post",
data:{id:id},
success:function () {
alert("deleted");
FetchAllUserUingAjax();
}
})
})
})
</script>
// but if I remove foreach (foreach) from controller and put it in view page, delete is working. I want to know what is my problem.
At the moment you set the click handler for the delete buttons, these buttons do not exist in the page (yet...) as they are being loaded with another ajax request.
To bind the buttons that are later added to the page, you can use event delegation. To do that, you need to change your click handler from this:
$(".deletenew").on("click",function () {
to:
$('body').on('click', '.deletenew', function () {
I have delegated it to the body element, but you can use any element that will contain the buttons and is already available on page load / DOM ready.
controller code
I think your alert is not showing because your table is showing by ajax In this code you have to use deletenew function, when click on delete button.
public function get_all_users()
{
if($this->input->post("action")=='FetchAllUserUingAjax1'){
$this->load->model("usersmodel");
$x= $data["allu"]=$this->usersmodel->ShowAllUsers("users");
foreach ($x as $a):
echo'<tr>
<td>'.$a->id.'</td>
<td>'.$a->username.'</td>
<td><button class="deletenew" id="'.$a->id.'" onclick="deletenew(this.id);">delete</button></td>
</tr>';
endforeach;
}
view page delete function
This is deletenew function this will work when you click on delete button
function deletenew(id){
alert("engex");
$.ajax({
url:"<?php echo base_url()?>Users/deleteusers",
method:"post",
data:{id:id},
success:function () {
alert("deleted");
FetchAllUserUingAjax();
}
})
}
I hope this code will work for you
//change Controller function
public function get_all_users()
{
if($this->input->post("action")=='FetchAllUserUingAjax1')
{
$this->load->model("usersmodel");
// print_r($this->input->post("action"));
echo ($this->input->post("action"));
$data["allu"]=$this->usersmodel->ShowAllUsers("users");
$this->load->view("template/admin/header");
//make another view show_users,make a button in page
//alluersusing ajax give that button id 'but'
$this->load->view("users/show_users,$data");
$this->load->view("template/admin/footer");
}
//copy paste the code below in show_users view
foreach ($x as $a):
echo'<tr>
<td>'.$a->id.'</td>
<td>'.$a->username.'</td>
<td><button class="btn btn primary" onclick=del(<?php echo '.$a->id.' ?>)>delete</button></td>
</tr>';
endforeach;
//Ajax Delete function
<script>
function del(id) {
$.ajax({
type: "POST",
url: '<?php echo base_url('Users/deleteusers')?>' +"/"+ id,
success: function (data) {
$("#get").html(data);
}
});
}
</script>

Jquery Updated table view after successfull operation

I have a table in a page for example:-
<tr>
<th>no</th>
<th>name</th>
<th>age</th>
<th>actions</th>
</tr>
<tr>
<td>$i</td>
<td>$name</td>
<td>$age</td>
<td>Delete</td>
</tr>
on the click of the delete it will go the controller through jquery and successfully delete the row, after that I want to show the updated table means without that deleted row. for this now I'm using another page and with the table data, on success I'm doing like this:
$(.updated_table_view).html(data.view);
is there any other simple way to do this like without an another page?
Presumably "...will go the controller through jquery..." means via Ajax, so if you want it to just do a simple removal, just hide the row:
jsFiddle: https://jsfiddle.net/842x2wuc/
<script>
$(document).ready(function(){
$('.delete').click(function(e) {
e.preventDefault();
var thisBtn = $(this);
$.ajax({
url: '/link/to/delete.php',
type: 'post',
data: { id: thisBtn.attr('href') },
success: function(response) {
// This will fade out the row
thisBtn.closest('tr').fadeOut('fast');
}
});
});
});
</script>

Changing specific html table row by jquery.ajax

I have an HTML table generated by PHP querying from MySQL table.
<table>
<tr>
<th>Sl</th>
<th>ID</th>
<th>Article Name</th>
<th>Publish Status</th>
</tr>
<?php
$i = 1;
foreach ($obj->showAllFromTable('pattern') as $pattern) {
extract($pattern);
?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $id; ?></td>
<td><?php echo $pattern_name; ?></td>
<td id="publish_<?php echo $id; ?>" class="status_pattern">
<?php echo $publish; ?>
</td>
</tr>
<?php
}
?>
</table>
I want to change the status of any article by clicking on the 'publish' cell of the corresponding article row. I am trying to use ajax method of jquery for this purpose as shown in the following:
<script type="text/javascript">
$(document).ready(function(){
$('.status_pattern').click(function(){
var thisid = $(this).attr('id');
$.ajax({
url: "status_change_pattern.php",
data: {
id: thisid
},
success: function (response) {
alert(response);
}
});
});
});
</script>
In the "success" block, instead of "alert", I want to create a functionality to change the text of the specific cell which I clicked. The "status_change_pattern.php" has just a text "Hey Hey".
Can anyone help? Please.
Thanks.
You have to use closure to preserve the id.
<script type="text/javascript">
$(document).ready(function(){
$('.status_pattern').click(function(){
var thisid = $(this).attr('id');
$.ajax({
url: "status_change_pattern.php",
data: {
id: thisid
},
success: function (id) {
return function (response) {
$("#" + id).html(response);
}
}(thisid)
});
});
});
</script>
You need to write,
success: function (response) {
$(thisid).html(response);
}
Here in response, you need to get new status.
The solution provided by SajithNair works. Thanks to SajithNair. But it can also be done without using closure. As shown below:
$('.status_pattern').click(function() {
var thisid = $(this).attr('id');
$.ajax({
url : "status_change_pattern.php",
data : {
id : thisid
},
success : function(response) {
$('#' + thisid).html(response);
}
});
});
Thanks

Categories