delete data using ajax and codeigniter - php

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>

Related

Fetch data using AJAX and Codeigniter?

I am trying to fetch data into a table and nothing happens.
No table appears
No data is fetched
Controller
public function indexajax()
{
if($this->input->post("action")=='FetchAllUserUingAjax')
{
$this->load->model("usersmodel");
$data["allu"]=$this->usersmodel->ShowAllUsers("users");
$data['pagetitle']=" -->All Users Using Ajax<--";
foreach ($allu as $a):
echo'<tr>
<td>'.$a->id.'</td>
<td>'.$a->username.'</td>
</tr>';
endforeach;
$this->load->view("template/admin/header",$data);
$this->load->view("users/allusersusingajax",$data);
$this->load->view("template/admin/footer");
}
}
jQuery
<script>
$(document).ready(function () {
FetchAllUserUingAjax();
function FetchAllUserUingAjax() {
$.ajax({
url:'<?php echo base_url()?>Users/indexajax',
method:"post",
success:function (data) {
$(".userdataajax table").append(data);
}
})
var action="FetchAllUserUingAjax";
$.ajax({
url:"<?php echo base_url()?>Users/indexajax",
method:"post",
data:{action:action},
success:function (data) {
$(".userdataajax table tr ").not("table tr:first").remove();
$(".userdataajax table").append(data);
Table();
}
})
}
})
</script>
Model
public function ShowAllUsers()
{
$sql=$this->db->get("users");
return $sql->result();
}
View
<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>
Your code hints at other relevant code that is not shown. I'm taking what you show as all that needs to be known. Here's what I see based on that premise.
First, the view. Add an id to the table. It makes JQuery selectors so much easier. The JavaScript is in this file which is "users/allusersusingajax.php".
<div class="userdataajax table-responsive">
<table id='user-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 () {
function FetchAllViaAjax() {
$.ajax({
url: '<?= base_url("users/get_all_users") ?>',
method: "post",
dataType: 'html',
success: function (data) {
var table = $("#user-table");
table.not("table tr:first").remove();//your code makes it unclear why you need this
table.append(data);
}
});
FetchAllViaAjax();
}
});
</script>
The controller needs two methods. One to show the table another to get the rows. This is the file Users.php
//show the page which includes the basic <table> and header row
public function indexajax()
{
// The code and question text give no reason for this conditional test
// So I'm removing it
//if($this->input->post("action") == 'FetchAllUserUingAjax')
//{
$data['pagetitle'] = "-->All Users Using Ajax<--";
$this->load->view("template/admin/header", $data);
$this->load->view("users/allusersusingajax");
$this->load->view("template/admin/footer");
//}
}
//respond to ajax request
public function get_all_users()
{
$this->load->model("usersmodel");
$allu = $this->usersmodel->ShowAllUsers("users");
$out = ''; //if the model returned an empty array we still have a string to echo
//using PHP's output buffer to simplify creating a big string of html
ob_start(); //start output buffering
foreach($allu as $a):
?>
<tr><td><?= $a->id; ?></td><td><?= $a->username; ?></td></tr>
<?php
endforeach;
$out .= ob_get_clean(); //append the output buffer to the $out string
echo $out;
}
Read about PHP's Output Control Functions
I'd first update my model to return an array:
return $sql->result_array();
Then in your controller, you don't need to load a view:
public function indexajax()
{
if($this->input->post("action")=='FetchAllUserUingAjax')
{
//set content type
header("Content-type: application/json");
$this->load->model("usersmodel");
echo json_encode(
$this->usersmodel->ShowAllUsers(); //this method doesn't expect an argument, no need to pass one
);
}
}
Then in your ajax callback:
success: function(resp){
$.each(resp, function(k,v){
console.log(v);
});
}

Adding data using codeigniter and ajax

I am new in codeigniter I want to retrieve data into table using ajax
but no result found please help me to solve my problem
this is controller code
public function indexajax()
{
$this->load->model("usersmodel");
$data['pagetitle']=" -->All Users Using Ajax<--";
$this->load->view("template/admin/header");
$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");
// print_r($this->input->post("action"));
echo ($this->input->post("action"));
$data["allu"]=$this->usersmodel->ShowAllUsers("users");
foreach ($allu as $a):
echo'<tr>
<td>'.$a->id.'</td>
<td>'.$a->username.'</td>
<td><button class="deletenew" id="'.$a->id.'">deletenew</button></td>
</tr>';
endforeach;
}
}
}
this is my model code
public function ShowAllUsers()
{
//$this->db->order_by("id", "desc");
// $this->db->limit(20);
$sql=$this->db->get("users");
return $sql->result();
}
This is my view code
this is my HTML
<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>
this is my ajax calling trying to retrieve and delete data
<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 () {
var id=$(this).attr('id');
$.ajax({
url:'<?php echo base_url()?>Users/deleteusers',
method:"post",
data:{id:id},
success:function () {
FetchAllUserUingAjax();
}
})
})
})
</script>
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");
}
<script>
$("#but").click(function() {
$.ajax({
type: "POST",
url: "<?php echo base_url()?>Users/get_all_users",
success: function(data) {
$("#get").html(data);
//console.log(data);
}
});
});
</script>
//add below code to 'show_users' page or view
<?php foreach ($allu as $a):
echo'<tr>
<td>'.$a->id.'</td>
<td>'.$a->username.'</td>
<td><button class="deletenew" id="'.$a->id.'">deletenew</button></td>
</tr>';
endforeach;
//hope this will help

Delete form data not working

My function jQuery include on my head html
$(function() {
$(".deletePage").click(function() {
var pageId = $(this).attr("id");
$.ajax({
type: "post",
url: "delete_page.php",
cache: false,
data:'id=' + pageId,
success: function(response){
try{
if(response=='true'){
parent.slideUp('slow', function() {$(this).remove();});
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}
}
And my html with listPage
<table class="table table-hover">
<thead>
<tr>
<td><strong>title page</strong></td>
<td><strong>URL</strong></td>
<td><strong>Edit</strong></td>
<td><strong>Delete</strong></td>
</tr>
</thead>
<tbody>
<?php
while($row_Q = mysql_fetch_array($sql_Q)){
?>
<tr>
<td><?php echo $row_Q["title"]; ?></td>
<td><?php echo $row_Q["permalink"]; ?></td>
<td>
</td>
<td>
<button type="button" class="btn btn-danger">
<a class="deletePage" href="#">Delete</a>
</button>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
Why not working jQuery and not delete selected page?Any help me please?I want that click on the button "DELETE" the row its delete without going other page
thank you
You have an error. You're trying to get the page ID, but it doesn't exist in your HTML code.
Add the ID to your <a> and you're set.
I fix the problem :)
You said to me that add the Id to me and yes this is a one problem but I have more problems.
This is my new function in jQuery
$(function() {
$(".deletePage").click(function() {
var pageId = $(this).attr("id");
var parent = $(this).parent();
if(confirm("Delete me?")){
$.ajax({
type: "post",
url: "delete_page.php",
cache: false,
data: 'id=' + pageId,
dataType: "text",
success: function(response){
location.reload();
try{
if(response=='true'){
parent.slideUp('slow', function() {$(this).remove();});
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}
return false;
});
});

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

Deleting users from the database using AJAX and Codeigniter

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

Categories