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);
});
}
Related
I am trying to get dataTables to process my table in Laravel using an ajax script, I have no pages of search function.
'datatables.min.js' pulls through in chrome dev sources from CDN and I know my ajax is working because other scripts work fine on the page.
I am using some basic custom CSS on the table via a custom.css file, but I was under the impression that is fine.
My controller code.
// FETCH ALL AJAX REQUEST
public function fetchAll()
{
$vehicles = Vehicle::all(); //Could be model or controller...
$output = '';
if ($vehicles->count() > 0) {
$output .= '<table #"showAll" class="veh-table table table-striped table-sm text-center align-middle" >
<thead>
<tr>
<th class="tbl-head">ID</th>
<th class="tbl-head">Image</th>
<th class="tbl-head">Make</th>
<th class="tbl-head">Model</th>
<th class="tbl-head">Derivative</th>
<th class="tbl-head">Powertrain</th>
<th class="tbl-head">Transmission</th>
<th class="tbl-head">Fuel Type</th>
<th class="tbl-head">Model Year</th>
<th class="tbl-head"><i class="bi-gear-fill h5"></i></th>
</tr>
</thead>
<tbody>';
foreach ($vehicles as $vehicle) {
$output .= '<tr class="tbl exp_tbl">
<td>'.$vehicle->id.'</td>
<td><img src="./storage/images/'.$vehicle->image.'" class="img-thumbnail justify-content-sm-center"></td>
<td>'.$vehicle->make.'</td>
<td>'.$vehicle->model_name.'</td>
<td>'.$vehicle->version.'</td>
<td>'.$vehicle->powertrain.'</td>
<td>'.$vehicle->trans.'</td>
<td>'.$vehicle->fuel.'</td>
<td>'.$vehicle->model_year.'</td>
<td>
<i class="bi-pencil-square h6"></i>
<i class="bi-trash h6"></i>
</td>
</tr>';
}
$output .= '</tbody></table>';
echo $output;
} else {
echo '<h1 class="text-center text-secondary my-5">No vehicles in the database!</h1>';
}
}
The function from my html.
...
$(function() {
...
// SHOW ALL VEHICLES AJAX REQUEST
fetchAllVehicles();
function fetchAllVehicles(){
$.ajax({
url: '{{route('fetchAll')}}',
method: 'GET',
success: function(res){
$("#show_all_vehicles").html(res);
$("#showAll").DataTable({
order: [ 0, "desc" ]
});
}
});
}
...
}
...
I have tried adding
{
dataType: 'json',
processData: true, // & false...
serverSide: false, // & true...
}
Please let me know if I haven't included some needed information.
Try to change
$output .= '<table #"showAll"....
to
$output .= '<table id="showAll"....
and let me know if that works
I am using Ajax request to fetch data from database. All I want to do is to display the result in tabular form whenever we select an option from the option list. I am also able to do that but when I am choosing another option the view for the previous option it is not removed from the table.
View:
$('#city').on('change',function(){
var cityID = $(this).val();
// alert(cityID);
$.ajax({
type:'POST',
url:'<?php echo base_url('bank/getBranchDetail'); ?>',
data:'city_id='+cityID,
success:function(data){
var dataObj = jQuery.parseJSON(data);
$(dataObj).each(function(){
var ifsc = $('<p />');
var micr = $('<p />');
var contact = $('<p />');
var address = $('<p />');
// alert(option);
ifsc.attr('value', this.id).text(this.ifsc_code);
micr.attr('value', this.id).text(this.micr_code);
contact.attr('value', this.id).text(this.contact_no);
address.attr('value', this.id).text(this.address);
$('#ifsc').append(ifsc);
$('#micr').append(micr);
$('#contact').append(contact);
$('#address').append(address);
});
// $('#hodm_results').html(data);
}
});
});
<table class="table table-bordered table-hover table-full-width" id="table_userinfo">
<thead>
<tr>
<th>IFSC Code</th>
<th>MICR Code</th>
<th>Contact No.</th>
<th>Address</th>
</tr>
<tr>
<td id="ifsc"></td>
<td id="micr"></td>
<td id="contact"></td>
<td id="address"></td>
</tr>
</thead>
</table>
Controller:
public function getBranchDetail(){
$branch = array();
$city_id = $this->input->post('city_id');
if($city_id){
$con['conditions'] = array('id'=>$city_id);
$branchData = $this->Bank_model->getBranchData($con);
}
echo json_encode($branchData);
}
Model:
function getBranchData($params = array()){
$this->db->select('c.micr_code, c.ifsc_code, c.contact_no, c.address');
$this->db->from($this->branchTbl.' as c');
//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach ($params['conditions'] as $key => $value) {
if(strpos($key,'.') !== false){
$this->db->where($key,$value);
}else{
$this->db->where('c.'.$key,$value);
}
}
}
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
//return fetched data
return $result;
}
When I am selecting a city from option it is showing me the result for that city which is correct. When I am choosing another city from the option it is showing the result also, but the result for the previous option is not removed from the table. I want to remove the previous record when I am selecting another option.
Check the below code ( not tested ). Clear the contents before appending data in the loop.
$('#city').on('change',function(){
var cityID = $(this).val();
// alert(cityID);
$.ajax({
type:'POST',
url:'<?php echo base_url('bank/getBranchDetail'); ?>',
data:'city_id='+cityID,
success:function(data){
var dataObj = jQuery.parseJSON(data);
// clear the data before appending
$('#ifsc').html("");
$('#micr').html("");
$('#contact').html("");
$('#address').html("");
$(dataObj).each(function(){
var ifsc = $('<p />');
var micr = $('<p />');
var contact = $('<p />');
var address = $('<p />');
// alert(option);
ifsc.attr('value', this.id).text(this.ifsc_code);
micr.attr('value', this.id).text(this.micr_code);
contact.attr('value', this.id).text(this.contact_no);
address.attr('value', this.id).text(this.address);
$('#ifsc').append(ifsc);
$('#micr').append(micr);
$('#contact').append(contact);
$('#address').append(address);
});
// $('#hodm_results').html(data);
}
});
});
<table class="table table-bordered table-hover table-full-width" id="table_userinfo">
<thead>
<tr>
<th>IFSC Code</th>
<th>MICR Code</th>
<th>Contact No.</th>
<th>Address</th>
</tr>
<tr>
<td id="ifsc"></td>
<td id="micr"></td>
<td id="contact"></td>
<td id="address"></td>
</tr>
</thead>
</table>
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 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
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
}