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
Related
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>
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);
});
}
I am doing a project for my school subject. I am confused on how to do checking data's in checkbox and when I press a submit button, it will loop to insert into my database. I manage to display/alert the data that is being checked in my data-table.
Here is my Contoller where it populates my data table:
public function getalldocs() {
$listdocs = $this->Admin_model->getdoctors();
$data = array();
foreach ($listdocs as $docs) {
$row = array();
$row[] = $docs->user_fname;
$row[] = $docs->user_mname;
$row[] = $docs->user_lname;
$row[] = '<input name="user_id[]" value="'.$docs->user_id.'" type="checkbox">';
$data[] = $row;
}
$output = array(
"data" => $data,
);
echo json_encode($output);
}
Here is in my view:
<div class="dataTable_wrapper">
<table id="dataTables-docs" class="table table-striped table-bordered table-hover dataTable dtr-inline" role="grid" style="width: 100%;" width="100%" aria-describedby="dataTables-material">
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div><!-- dataTable_wrapper -->
here is my javascript to echo the selected check box from my data-table:
function show_docs() {
$("#dataTables-docs").dataTable().fnDestroy();
table = $('#dataTables-docs').DataTable({
"ajax": {
"url": "<?php echo site_url('admin_controls/getalldocs')?>",
"type": "POST",
},
responsive: true,
className: 'select-checkbox',
'bInfo': false,
'paging': false
});
}
$('#dataTables-docs tbody').on('click', 'input[type="checkbox"]', function(e){
var user_id = $(this).val();
alert(user_id);
});
now, i want to all that is being checked to be inserted in my database like this:
(myid,selectedfromcheckbox);
here is my screenshot from database table:
Use another ajax to insert the data
$('#dataTables-docs tbody').on('click', 'input[type="checkbox"]', function(e){
var user_id = $(this).val();
$.ajax({
type:"post",
data: {user_id:user_id},
"url": "<?php echo site_url('admin_controls/saveData')?>",
success:function(data){
$("#info").html(data);
}
});
});
// Below code in you controller
public function saveData()
{
// code to save in controler
}
I have a basic table (data simplified to attempt to locate problem) which uses jquery .ajax in order to allow data to be inputted, deleted and modified live. This used to work fine however I have recently moved over to PDO instead of mysqli and subsequently converted this code, however it is not working as intended. The fetch_data() function I have created doesn't get the most recent inserted (even after a refresh + it IS in database) meaning the data is incomplete. Wondering if anyone could help.
EDIT 1: Just to be clear, it is only the latest data entry which does not appear, even once the page has been refreshed. That data entry does show however once another new entry has been inputted. (so there is like a buffer of 1 entry before it shows on the table)
index.php
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
var first_name = $('#first_name').text();
var last_name = $('#last_name').text();
if(first_name == '')
{
alert("Enter First Name");
return false;
}
if(last_name == '')
{
alert("Enter Last Name");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{first_name:first_name, last_name:last_name},
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
function edit_data(id, text, column_name)
{
$.ajax({
url:"edit.php",
method:"POST",
data:{id:id, text:text, column_name:column_name},
dataType:"text",
success:function(data){
alert(data);
}
});
}
$(document).on('blur', '.first_name', function(){
var id = $(this).data("id1");
var first_name = $(this).text();
edit_data(id, first_name, "first_name");
});
$(document).on('blur', '.last_name', function(){
var id = $(this).data("id2");
var last_name = $(this).text();
edit_data(id,last_name, "last_name");
});
$(document).on('click', '.btn_delete', function(){
var id=$(this).data("id3");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
select.php
$dbc = new PDO("mysql:host=".DBHOST.";port=3306;dbname=".DBNAME, DBUSER, DBPASS);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$output = '';
$dbq = $dbc->prepare('SELECT * FROM tbl_sample ORDER BY id DESC');
$dbq->execute();
$dbq->fetch(PDO::FETCH_ASSOC);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">First Name</th>
<th width="40%">Last Name</th>
<th width="10%">Delete</th>
</tr>';
if($dbq->fetchColumn() > 0)
{
while($row = $dbq->fetch(PDO::FETCH_ASSOC))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="first_name" data-id1="'.$row["id"].'" contenteditable>'.$row["first_name"].'</td>
<td class="last_name" data-id2="'.$row["id"].'" contenteditable>'.$row["last_name"].'</td>
<td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="first_name" contenteditable></td>
<td id="last_name" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else
{
$output .= '
<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
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;
});
});