Laravel Ajax Search Query Param Issue - php

Trying to create/learn ajax search results using Laravel. Im at the following stage where I can get the data from the DB but the query string appears to not be captured into the controller and querying the data. I expect its an issue with my Ajax or where I am posting the data from the view to the URL. I am new to Laravel so any advice will be welcome. Thanks
search.blade.php
<form class="navbar-search">
<div class="input-group">
<input type="text" class="form-control bg-lightblue border-0 small text-white border-dark" name="search" id="search" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-success" type="button"></button>
</form>
<div class="col-md-12">
<table class="table table-hover table-responsive-sm">
<thead class="thead-dark">
<tr>
<th scope="col">Total Data : <span id="total_records"></span></th>
<th scope="col">Company Name</th>
<th scope="col">Immediate Contact</th>
<th scope="col">Address</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('search.action') }}",
//url: 'user-figures/action',
method: 'GET',
data: {"query":query},
dataType:'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
});
</script>
Controller
public function ajaxindex()
{
return view('search.index');
}
public function ajaxaction(Request $request)
{
if($request->ajax())
{
$total_row = '';
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = figures::where('name', 'like', '%'.$query.'%')
->get();
}
else
{
$data = figures::orderBy('id', 'desc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->name.'</td>
<td>poopppp</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
return response()->json($data);
// $str_data = implode(" ", $data);
// echo $str_data;
}
}
web.php
Route::get('/search', 'figuresController#ajaxindex')->name('search');
Route::get('/search/action', 'figuresController#ajaxaction')->name('search.action');

I used your code and followed this tutorial https://www.cloudways.com/blog/live-search-laravel-ajax/ and have got this to work. Here is my full code and hopefully you can figure out how to get yours working
Search controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Product;
class SearchController extends Controller
{
public function index()
{
return view('search.index');
}
public function search(Request $request)
{
if($request->ajax())
{
$output="";
$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
if($products)
{
foreach ($products as $key => $product) {
$output.='<tr>'.
'<td>'.$product->id.'</td>'.
'<td>'.$product->title.'</td>'.
'<td>'.$product->description.'</td>'.
'<td>'.$product->price.'</td>'.
'</tr>';
}
return Response($output);
}
}
}
}
Just one view file
<!DOCTYPE html>
<html>
<head>
<meta name="_token" content="{{ csrf_token() }}">
<title>Live Search</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Products info </h3>
</div>
<div class="panel-body">
<div class="form-group">
<input type="text" class="form-controller" id="search" name="search"></input>
</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{URL::to('search/action')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
})
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
</body>
</html>
Routes
Route::get('/search','SearchController#index');
Route::get('/search/action','SearchController#search')->name('search.action');

Related

Batch Process not inserted to the table

I have following tables that used to store purchase & issue of items.
store_update_stock Table
+-----------------+----------+-------------------+-----------------+--------+
| update_stock_id | supplier | user order_status | transfer_status | status |
+-----------------+----------+-------------------+-----------------+--------+
store_update_stock_details Table
+-------------------------+-----------------+------+-----+------------+--------+
| update+stock_details_id | update_stock_id | item | qty | unit_price | status |
+-------------------------+-----------------+------+-----+------------+--------+
02) I used Codeigniter for the project and files as follows :
Controller
public function verifyItemReqFromHD()
{
$this->checkPermissions('edit', 'issueApprovedItem');
$bc = array(array('link' => '#', 'page' => 'Item Request From HD'));
$meta = array('page_title' => 'Item Request From HD', 'bc' => $bc);
$this->data['products'] = $this->Item_model->getProducts();
if ($this->form_validation->run() == true) {
$count = count($this->input->post('item'));
$items = $this->input->post('item');
$qts = $this->input->post('qty');
$up = $this->input->post('unit_price');
$total = 0;
for ($x = 0; $x < $count; $x++) {
$details[$x]['update_stock_id'] = null;
$details[$x]['item'] = $items[$x];
$details[$x]['qty'] = $qts[$x];
$details[$x]['unit_price'] = $up[$x];
$details[$x]['status'] = 1;
}
$stock = array(
'supplier' => $this->session->userdata('id_user'),
'user' => ucfirst($this->session->userdata('name')),
'order_status' => 'verifyIssue',
'transfer_status' => 'Verified',
'status' => '1'
);
if ($this->Item_model->addItemReqFromHD($stock, $details)) {
$this->session->set_flashdata('message', 'Successfully Sent Your Request..!!');
redirect('item/verifyItemReqFromHD');
}
} else {
$this->session->set_flashdata('error', validation_errors());
$this->render('item/viewItemtoIssued', $meta, $this->data);
}
}
Model
function addItemReqFromHD($data,$details)
{
$this->db->trans_start();
if ($this->db->insert('store_update_stock', $data)) {
$id = $this->db->insert_id();
foreach ($details as $detail) {
$detail['update_stock_id'] = $id;
$this->db->insert('store_update_stock_details', $detail);
}
}
$this->db->trans_complete();
if ($this->db->trans_status() === true) {
return true;
}
return false;
}
View
<?php
if(!empty($issueData)){
$common=$issueData[0];
}
?>
<script type="text/javascript">
$(document).on("change", "#item", function () {
$.ajax({
'url': '<?=site_url("item/isExistProduct/?q=")?>' + $('#item').val(),
'method': 'GET',
'success': function (data) {
var jData = JSON.parse(data);
if (jData.status == true) {
jData.data.forEach(data => {
$('#request_table').append('<tr>' +
'<td ><span id="product" >' + data.item_name + '</span>' +
'<input type="hidden" id="item[]" name="item[]" value="' + data.item_id + '">' +
'</td>' +
'<td class="text-center">' + data.qty + '</td>' +
'<td class="text-center"><input class="form-control text-right" disabled id="sales_price[]" name="sales_price[]" value="' + data.up+ '"></td>' +
'<td class="text-center"><input class="form-control text-center rquantity" data-qty-bal="' + data.qty + '" autofocus required type="number" step="any" id="qty[]" name="qty[]" ></td>' +
'<td class="text-center" ><i class="fa fa-remove remove" style="cursor: pointer"></i></td>' +
'</tr>');
})
}
},
'error': function () {
}
});
});
$(document).on("click", ".remove", function () {
$(this).closest('tr').remove();
});
var old_row_qty;
$(document).on("focus", '.rquantity', function () {
old_row_qty = $(this).val();
}).on("change", '.rquantity', function () {
var row = $(this).closest('tr');
var issue_q = parseFloat($(this).val());
var available_q = parseFloat($(this).data('qty-bal'));
if (issue_q > available_q) {
console.log("ssss");
$(row).addClass('danger');
$('#add_sale').attr('disabled', true);
alert("Can not proceed your request ..!!. Issue quantity is higher than the available quantity..");
} else {
console.log("remove");
$(row).removeClass('danger');
$('#add_sale').attr('disabled', false);
}
});
</script>
<!-- Main content -->
<section class="invoice">
<!-- title row -->
<div class="row">
<div class="col-xs-12">
</div>
<!-- /.col -->
</div>
<!-- Table row -->
<div class="row" style="margin-top: 2%">
<div class="col-xs-12 table-responsive">
<table class="table table-striped">
<thead>
<tr class="" style="background-color: #33ff99 !important;">
<th>Item</th>
<th class="text-right">Requested Qty</th>
<th class="text-right">Approved Qty</th>
</tr>
</thead>
<tbody>
<?php
if (!empty($issueData)) {
foreach ($issueData as $rows){
?>
<tr>
<td style="width: 40%"><?=$rows->item_name?></td>
<td style="width: 15%" class="text-right"><?=$rows->r_qty+0?></td>
<td style="width: 15%" class="text-right"><?=$rows->ap_qty+0?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<form action="<?= site_url('item/verifyItemReqFromHD') ?>" method="post">
<div class="col-md-5">
<div class="form-group"><label>Select Item</label>
<select name="item" id="item" class="form-control select2" required>
<option value="">Select Item</option>
<?php
if (!empty($products)) {
foreach ($products as $row) {
?>
<option value="<?= $row->item_id ?>"><?= $row->item_name ?></option>
<?php
}
}
?>
</select>
</div>
</div>
<div class="col-md-12 column">
<div class="col-md-12">
<div class="control-group table-group">
<label class="table-label">Issue Items *</label>
<div class="controls table-controls">
<table id="request_table"
class="table items table-striped table-bordered table-condensed table-hover">
<thead>
<tr class="" style="background-color: #ff66a3 !important;">
<th class="col-md-5">Item Name</th>
<th class="text-center col-md-2">Available Qty</th>
<th class="text-center col-md-2">Unit Price</th>
<th class="text-center col-md-2">Issuing Qty</th>
</th>
<th class="col-md-2" style="width: 30px !important; text-align: center;">
<i class="fa fa-trash-o" style="opacity:0.5; filter:alpha(opacity=50);"></i>
</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr id="tfoot" class="tfoot active">
<th colspan="2">Total</th>
<th class="text-right"></th>
<th class="text-center">0</th>
<th class="text-center"><i class="fa fa-trash-o"
style="opacity:0.5; filter:alpha(opacity=50);"></i>
</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8"></div>
<div class="col-md-4">
<button type="submit" id="add_sale" class="btn btn-primary btn-block">Issue</button>
</div>
</div>
</form>
</section>
Desired Output
03) Then I need to insert data to the both tables using above codes.
When press "Issue" button in the view the relevant values didn't insert to the tables. What can be going wrong ? Can anyone help me ?
Try
$this->db->trans_commit()
I added the following validation to the controller.
$this->form_validation->set_rules('item', 'Item', 'required');
And also changed the following line in my view.
'<input type="hidden" id="item_id[]" name="item_id[]" value="' + data.item_id + '">' +
Solved the problem .....

Angularjs ng-click not working in laravel #PHP

I have just created a very simple app. It only contains one function which is used in ng-click. Somehow, ng-click is not firing. Can anyone take a look for me?
<div class="form-inline">
<label for="primary" style="padding-right:5px">Primary skill </label>
<select id="primary" class="form-control" ng-model="primary" id="primary" ng-options="s.skill_name for s in skills| excludeFrom:secondary"></select>
<label for="secondary">Secondary skill </label>
<select id="secondary" class="form-control " id="secondary" ng-model="secondary" ng-options="s.skill_name for s in skills| excludeFrom:primary"></select>
<div ng-controller="profileController">
<input type="button" value="Search" class="mx-sm-3 btn btn-primary" ng-model="searchbtn" name="search" ng-click="profileController.getprofile()">
<table class="table" id="myTable">
<tr>
<th>Full name</th>
<th>Email</th>
<th>City</th>
<th>Primary skill1</th>
<th>Primary skill2</th>
<th>Primary skill3</th>
<th>Secondary skill1</th>
<th>Secondary skill2</th>
<th>Secondary skill3</th>
<th>Secondary skill4</th>
<th>Secondary skill5</th>
</tr>
<tr ng-repeat="p in profiles">
</tr>
</table>
</div>
</div>
<script>
function profileController($scope, $http) {
$scope.getprofile = function() {
var pskill = $("#primary").val();
var skill = $("#secondary").val();
$http({
url: "{{PROFILE_REPOSITORY}}",
method: "POST",
data: { "_token": { { csrf_token() } }, 'primary': pskill, 'secondary': skill },
}).then(function(response) {
$scope.profiles = response.data;
console.log(response.data);
}),
function(response) {
console.log('failed');
}
}
}
</script>
<div class="form-inline">
<label for="primary" style="padding-right:5px">Primary skill </label>
<select id="primary" class="form-control" ng-model="primary" id="primary" ng-options="s.skill_name for s in skills| excludeFrom:secondary"></select>
<label for="secondary">Secondary skill </label>
<select id="secondary" class="form-control " id="secondary" ng-model="secondary" ng-options="s.skill_name for s in skills| excludeFrom:primary"></select>
<div ng-controller="profileController">
<input type="button" value="Search" class="mx-sm-3 btn btn-primary" ng-model="searchbtn" name="search" ng-click="getprofile()">
<table class="table" id="myTable">
<tr>
<th>Full name</th>
<th>Email</th>
<th>City</th>
<th>Primary skill1</th>
<th>Primary skill2</th>
<th>Primary skill3</th>
<th>Secondary skill1</th>
<th>Secondary skill2</th>
<th>Secondary skill3</th>
<th>Secondary skill4</th>
<th>Secondary skill5</th>
</tr>
<tr ng-repeat="p in profiles">
</tr>
</table>
</div>
</div>
<script>
function profileController($scope, $http) {
$scope.getprofile = function() {
var pskill = $("#primary").val();
var skill = $("#secondary").val();
$http({
url: "{{PROFILE_REPOSITORY}}",
method: "POST",
data: { "_token": { { csrf_token() } }, 'primary': pskill, 'secondary': skill },
}).then(function(response) {
$scope.profiles = response.data;
console.log(response.data);
}),
function(response) {
console.log('failed');
}
}
}
</script>

Live Search Codeigniter not Working

I am a fresh graduate I am studying Codeigniter for the first time and I am having a hard time pls help me to fix my issue. I created a system that records employees information. I included a live search in my code. There are no error in syntax but there is no results shown. Below is my code.
Here is the controller. It's file name is Crud.php
Controller
public function fetch()
{
$output = '';
$query = '';
if($this->input->post('query'))
{
$query = $this->input->post('query');
}
$data = $this->Crudmodel->fetch();
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Job Title</th>
</tr>
';
if($data->num_rows() > 0)
{
foreach($data->result() as $row)
{
$output .= '
<tr>
<td>'.$row->fname.'</td>
<td>'.$row->lname.'</td>
<td>'.$row->job_title.'</td>
</tr>
';
}
}
else
{
$output .= '<tr>
<td colspan="5">No Data Found</td>
</tr>';
}
$output .= '</table>';
echo $output;
}
Here is the model. File name: Crudmodel.php
Model
public function fetch_data($query){
$this->db->select("*");
$this->db->from("employees");
if($query != ''){
$this->db->or_like('fname', $query);
$this->db->or_like('lname', $query);
$this->db->or_like('job_title', $query);
}
$this->db->order_by('id');
return $this->db->get();
}
View
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Employee Registation</h2>
</div><br>
<div class="pull-right">
<a class="btn btn-success" href="<?php echo base_url('crud/create') ?>"> Add Employee</a>
<a type="button" class="btn btn-danger" href="crud/logout">Logout</a>
</div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Search Employee" class="form-control" />
</div>
</div>
<div id="result"></div>
<div style="clear:both"></div>
<table class="table table-bordered">
<thead>
<tr>
<!-- <th>Full Name</th> -->
<th>First Name</th>
<th>Last Name</th>
<th>Job Title</th>
<th width="220px">Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $employees)
{
?>
<tr>
<td> <?php echo $employees->fname; ?></td>
<td> <?php echo $employees->lname; ?></td>
<td> <?php echo $employees->job_title; ?></td>
<td>
<form method="DELETE" action="<?php echo base_url('crud/delete/'.$employees->id); ?>">
<a class="btn btn-info" href="<?php echo base_url('crud/show/'.$employees->id) ?>"> View</a>
<a class="btn btn-primary" href="<?php echo base_url('crud/edit/'.$employees->id) ?>"> Edit</a>
<button type="submit" class="btn btn-danger"> Delete</button>
</form>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
<script>
$(document).ready(function () {
load_data();
function load_data(query)
{
$.ajax({
url: "<?php echo base_url('crud/fetch'); ?>",
method: "POST",
data: {query: query},
success: function (data) {
$('#result').html(data);
}
})
}
$('#search_text').keyup(function () {
var search = $(this).val();
if (search != '')
{
load_data(search);
} else
{
load_data();
}
});
});
</script>
Please help me to figure it out. Your help will be appreciated!
First, in your controller you are trying to call a method that may not exist:
$data = $this->Crudmodel->fetch();
Because in your model the method is named "fetch_data". So I think you intend to do this:
$data = $this->Crudmodel->fetch_data();
Second, you are not passing the query parameter to your model's method. It should be like this:
$data = $this->Crudmodel->fetch_data( $query );
These are two essential things that should help get you started.
Also note that it is not shown if crudmodel is loaded. You may need:
$this->load->model('crudmodel');
When you have a Crudmodel loaded, you don't need to uppercase your object usage. So in the end, you should probably have this line:
$data = $this->crudmodel->fetch_data( $query );
Besides the problems I pointed out in my other answer, I thought I'd help by cleaning things up a bit. Although not tested, this might help:
How about this:
Controller
public function fetch()
{
$data = $this->crudmodel->fetch_data();
echo $this->load->view('snippet', ['data' => $data], TRUE );
}
New view snippet.php
$output = '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Job Title</th>
</tr>
';
if( ! empty( $data ) )
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->fname.'</td>
<td>'.$row->lname.'</td>
<td>'.$row->job_title.'</td>
</tr>
';
}
}
else
{
$output .= '<tr>
<td colspan="5">No Data Found</td>
</tr>';
}
$output .= '</table>';
echo $output;
Model
public function fetch_data()
{
$query = $this->input->post('query');
$this->db->from("employees");
if( ! empty($query) )
{
$this->db->or_like('fname', $query);
$this->db->or_like('lname', $query);
$this->db->or_like('job_title', $query);
}
$this->db->order_by('id','ASC');
$data = $this->db->get();
if( $data->num_rows() > 0 )
return $data->result();
return NULL;
}
In your existing view
<script>
$(document).ready(function () {
load_data();
function load_data(query)
{
if(query == undefined)
query = '';
$.ajax({
url: "<?php echo site_url('crud/fetch'); ?>",
method: "POST",
data: {'query': query},
dataType: "html",
success: function (data) {
$('#result').html(data);
}
})
}
$('#search_text').keyup(function () {
var search = $(this).val();
if (search != '')
{
load_data(search);
} else
{
load_data();
}
});
});
</script>

search on table,real time

I have the below table:
<input type="search" class="light-table-filter" id="search" data-
table="order-table" placeholder="Kerko">
<table border="0" class=" table table-striped table-hover table-bordered table-condensed tableDemo bordered order-table table" >
<tr id="header">
<th>ID</th>
<th>emri</th>
<th>mbiemri</th>
<th>username</th>
<th>password</th>
<th>email</th>
<th>Nr Tel</th>
<th>ACTION</th>
</tr>
<?php
if(count($records)){
$i = 1;
$eachRecord= 0;
foreach($records as $key=>$eachRecord){
?>
<tr id="<?=$eachRecord['ID'];?>">
<td><?=$eachRecord['ID'];?></td>
<td class="Emri"><?=$eachRecord['Emri'];?></td>
<td class="Mbiemri"><?=$eachRecord['Mbiemri'];?></td>
<td class="Username"><?=$eachRecord['Username'];?></td>
<td class="Password"><?=$eachRecord['Password'];?></td>
<td class="Email"><?=$eachRecord['Email'];?></td>
<td class="nrtel"><?=$eachRecord['nrtel'];?></td>
<td>
<img src="" class="eimage"> <span class="glyphicon glyphicon-pencil"></span>
<img src="" class="dimage"> <span class="glyphicon glyphicon-trash"></span>
</td>
</tr>
<?php }
}
?>
</table>
Also,i want to make a real time search and i have the below jquery code:
<script type="text/javascript">
(function(document) {
'use strict';
var LightTableFilter = (function(Arr) {
var _input;
function _onInputEvent(e) {
_input = e.target;
var tables = document.getElementsByClassName(_input.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, _filter);
});
});
}
function _filter(row) {
var text = row.textContent.toLowerCase(), val = _input.value.toLowerCase();
row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
}
return {
init: function() {
var inputs = document.getElementsByClassName('light-table-filter');
Arr.forEach.call(inputs, function(input) {
input.oninput = _onInputEvent;
});
}
};
})(Array.prototype);
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
LightTableFilter.init();
}
});
})(document);
Everything it works perfectly.But I want to search all rows except the header of table that has id #header.I can't change the jquery code.Also I have tried some different jquery but only the above jquery code works perfect for me. The only issue is that the code when I write something,it find the row but the header hidded.

ngClick not working to multiple buttons using CodeIgniter framework

I'm new to Angularjs. I'm trying to call function onclick of the buttons. I used ng-click but it's not working. These buttons are dynamically created.
I'm implementing this application in CodeIgniter framework. Here is my code;
//view
<section class="content" ng-app="manageApp">
<div growl></div>
<div class="row" ng-controller="customerManageController">
<div class="col-md-12">
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Customers Information</h3>
</div>
<div class="box-body">
<table class="table table-striped table-bordered" id="customer_table" >
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Mobile</th>
<th>City</th>
<th>Email</th>
<th>Address1</th>
<th>Address2</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Name</th>
<th>Mobile</th>
<th>City</th>
<th>Email</th>
<th>Address1</th>
<th>Address2</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
//js file
var manageApp = angular.module('manageApp', ['ngRoute', 'angular-growl', 'ngAnimate']);
manageApp.controller('customerManageController', function ($scope, $http, growl) {
$http({
method: 'POST',
url: 'list_customers',
headers: {
"Content-Type": "application/json"
},
}).success(function (data) {
for(var i=0; i<data.length; i++) {
var tableBody = tableBody+('<tr id="'+data[i].id+'"><td>'+data[i].id+'</td><td>'+data[i].name+'</td><td>'+data[i].mobile+'</td><td>'+data[i].city+'</td><td>'+data[i].email+'</td><td>'+data[i].address1+'</td><td>'+data[i].address2+'</td><td><button ng-click="deleteFunc()" class="btn btn-danger"><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>');
}
$('#tableBody').html(tableBody);
$('#customer_table').DataTable();
});
$scope.deleteFunc = function () {
alert('here');
}
});
The problem is you're inserting new HTML that won't be bound to the controller. Anytime you insert new HTML code with Angular directives that isn't compiled, like you did with JQuery, it won't be bound to the controller unless you use the $compile function to bind it.
There is a way you can do this with your code but instead this should be refactored. You're waiting for data from a POST request before you render it. Instead of binding the HTML after you get the data (this is where $compile would be required) you can instead make use of a $scope which will contain an array of the data and render the HTML based on what is in that array.
The code would look like this:
<section class="content" ng-app="manageApp">
<div growl></div>
<div class="row" ng-controller="customerManageController">
<div class="col-md-12">
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Customers Information</h3>
</div>
<div class="box-body">
<table class="table table-striped table-bordered" id="customer_table" >
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Mobile</th>
<th>City</th>
<th>Email</th>
<th>Address1</th>
<th>Address2</th>
<th>Action</th>
</tr>
</thead>
<!-- Table now populates with data after it's received -->
<tbody id="tableBody">
<div ng-repeat="for data in receivedData">
<tr id="{{ data.id }}>
<td>{{data.id}}</td>
<td>{{data.name}}</td>
<td>{{data.mobile}}</td>
<td>{{data.city}}</td>
<td>{{data.email}}</td>
<td>{{data.address1}}</td>
<td>{{data.address2}}</td>
<td>
<button ng-click="deleteFunc()" class="btn btn-danger">
<i class="fa fa-trash" aria-hidden="true"></i>
</button>
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Name</th>
<th>Mobile</th>
<th>City</th>
<th>Email</th>
<th>Address1</th>
<th>Address2</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
JavaScript:
var manageApp = angular.module('manageApp', ['ngRoute', 'angular-growl', 'ngAnimate']);
manageApp.controller('customerManageController', function ($scope, $http, growl) {
// This will hold the data
$scope.receivedData = [];
$http({
method: 'POST',
url: 'list_customers',
headers: {
"Content-Type": "application/json"
},
}).success(function (data) {
// If here there is data, show it.
if (data.length > 0) {
$scope.receivedData = data;
}
}
});
$scope.deleteFunc = function () {
alert('here');
}
});

Categories