laravel and datatables can't integrate - javascript

Hi im having problem understand how to use datables in datatable.net in laravel.
Here is my Controller to generate the view
public function hospital()
{
$view = View::make('doctor.hospital', array());
return $view;
}
Here is my Controller for the datatable
public function allHospitalList()
{
$hospitals = HospitalList::hospitalsList();
return $hospitals;
}
Here is my Model
<?php
class HospitalList extends Eloquent {
protected $table = 'hospital_list';
public static function hospitalsList()
{
$data = HospitalList::join('Cities', 'Cities.id', '=', 'hospital_list.Address3')
->join('Province', 'Province.id', '=', 'hospital_list.Address4')
// ->paginate(10);
->get();
return $data;
}
}
and in my routes
Route::get('hospital',
array(
'uses'=>'DoctorController#hospital'
)
);
/* datatables */
Route::get('hospitallist',
array(
'as' => 'dt_hospital_all',
'uses'=>'DatatableController#allHospitalList'
));
and this is my table in the view
<table class="table table-hover radius" id="hospitaList">
<thead>
<tr>
<th>
</th>
<th>
Name
</th>
<th>
Type
</th>
<th>
Contact
</th>
</tr>
</thead>
<tbody>
<?php
foreach ($hospitals as $hospital)
{?>
<tr>
<td>
<!-- <span class="row-details row-details-close"></span> -->
<button type="button" class="btn red"><i class="fa fa-plus-square-o"></i>
</button>
</td>
<td>
{{ $hospital->name }}</br>
{{ $hospital->address1 }} {{ $hospital->address2 }}
<?php
if($hospital->address1 != '' || $hospital->address2 != '') echo "</br>";
?>
{{ $hospital->City }}, {{ $hospital->province }}
</td>
<td>
{{ $hospital->type }}
</td>
<td>
{{ $hospital->contact }}
</td>
</tr>
<?php
}
?>
</tbody>
</table>
and this is my javascript on the view
var url = "{{ URL::route('dt_hospital_all') }}";
$(document).ready(function() {
$('#hospitalList').dataTable( {
"processing": true,
"serverSide": true,
"ajax": url
} );
} );
im getting an error
Undefined variable: hospitals (View: /Applications/AMPPS/www/docsearch/app/views/doctor/hospital.blade.php)

Right now, you are referring to a non-exisiting variable, $hospitals.
You need to provide $hospitals to your View:
View::make('doctor.hospital')->with('hospitals', Hospital::all())
This assumes you have a Hospital model.

Related

Unable to fetch data from database using ajax function Laravel

I am trying to fetch data from the database using ajax call, but my function in jquery is not working for fetching the data and I am getting an error "data is not defined". I don't know what goes wrong. I am trying to fetch all data from the database table and display it on the screen Here is my controller
<?php
namespace App\Http\Controllers;
use Haruncpi\LaravelIdGenerator\IdGenerator;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use Illuminate\Support\Facades\DB;
use App\User;
use App\Models\patient;
use Illuminate\Support\Facades\Validator;
class SearchPatient extends Controller
{
function action(Request $request)
{
if ($request->ajax())
{
$query= $request->get('query');
if ($query != '')
{
$data = DB::table('patients')->first()
->where('patientid','like','%'.$query.'%' )
->orWhere('fname','like','%'.$query.'%')
->orWhere('lname','like','%'.$query.'%')
->orWhere('contactno','like','%'.$query.'%')
->orWhere('gender','like','%'.$query.'%')
->orWhere('cnic','like','%'.$query.'%')
->orWhere('city','like','%'.$query.'%')
->orWhere('address','like','%'.$query.'%')
->get();
}
else
{
$data = DB::table('patients')->first()
->orderBy('created_at', 'desc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>
'.$row->patientid.'
</td>
<td>
'.$row->fname.'
</td>
<td>
'.$row->lname.'
</td>
<td>
'.$row->cnic.'
</td>
<td>
'.$row->gender.'
</td>
<td>
'.$row->address.'
</td>
<td>
'.$row->contactno.'
</td>
<td>
'.$row->city.'
</td>
<td>
'.$row->created_at.'
</td>
</tr>
';
}
}
else
{
$output='
<tr>
<td align="center" colspan="5">
No Data Found
</td>
</tr>';
}
$data = array(
'table_data' => $output,
'table_data' => $table_data
);
echo json_encode($data);
}
}
}
Here is my ajax function
$(document).ready(function() {
fetch_patients('');
function fetch_patients(query = '')
{
$.ajax({
URL:"/action",
method: 'GET',
data: {query:query},
dataType: 'json',
success: function(data)
{
$('tbody').html(data.table_data);
$('total-patient-records').text(data.total_data);
}
})
}
$(document).on('keyup', '#searchpatient', function(){
var query = $(this).val();
fetch_patients(query);
})
});
Here is my route
Route::get('/action', [SearchPatient::class, 'action'])->name('action');
Route:: get ('/SearchPatient',function(){
return view ('SearchPatient');
});
Here is my blade file
<div class="container box">
<h3 align="center">Search Patient</h3><BR>
<div class="panel panel-default">
<div class="panel-heading">
Search Patient Data
</div>
<div class="panel-body">
<input type="text" name="searchpatient" id="searchpatient" class="form-control" placeholder="Search Patient">
</div>
<div class="table-responsive">
<h3 align="center">Total Data : <span id="total-patient-records"></span></h3>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Patient ID</th>
<th>Name</th>
<th>CNIC</th>
<th>Gender</th>
<th>Address</th>
<th>Contact No</th>
<th>City</th>
<th>Last Visit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
You have error in your code, double key 'table_data' and undefined variable $table_data
//Jquery
var data = {
"_token": $('input[name=_token]').val(),
query:query
};
$.ajax({
URL:"/action",
method: 'GET',
data: data,
dataType: 'json',
success: function(data)
{
$('tbody').html(data.table_data);
$('total-patient-records').text(data.total_data);
}
})
//controller
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
return response()->json(['data' => $data]);
var url = '{{ route('get_products') }}';
var data = {
"_token": $('input[name=_token]').val(),
};
$.ajax({
type: "get",
url: url,
data: data,
success: function(response) {
alert(response.data);
}
});
<------ controller ------>
public function get_products()
{
$data = DB::table('products)->get();
return response()->json(['data' => $products]);
}
here is the issue in the document-ready method the data variable is used but Never initialize before using it.
The solution in to pass fetch_patients('') an empty string in your method, instead of data (an undefined variable)

Not able to load details based on applied filters in ajax and laravel

I am new to Laravel and ajax and I am trying to apply Custom filters on Table data. I have followed this tutorial https://www.youtube.com/watch?v=XmUH049dk9I but unfortunately it's not working. I have used yajra data tables.
Here is my controller code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class CustomSearchController extends Controller
{
function index(Request $request)
{
if(request()->ajax())
{
if(!empty($request->Business_unit))
{
$data = DB::table('memberdetails')
->select('membersid','Role','Region','Orglevel1','Orglevel2')
->where('Business_unit',$request->Business_unit)
->get();
}
else
{
$data = DB:: table('memberdetails')
->select('membersid','Role','Region','Orglevel1','Orglevel2')
->get();
}
return datatables()->of($data)->make(true);
}
$Business_unit = DB::table('memberdetails')
->select('Business_unit')
->groupBy('Business_unit')
->orderBy('Business_unit', 'ASC')
->get();
return view('admin.members.test', compact('Business_unit'));
}
}
This is my view
#extends('layouts.admin')
#section('content')
<div class="row">
<div class="col">
<div class="form-group">
<select name="Business_unit" id="Business_unit" class="form-control">
<option value="">Business Unit</option>
#foreach($Business_unit as $Bu)
<option value="{{ $Bu->Business_unit }}">{{ $Bu->Business_unit}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<button class="btn btn-primary rounded" type="button" id="search" name="search">Apply</button>
</div>
<div class="form-group">
<button class="btn btn-primary rounded" type="button" id="reset" name="reset">Reset</button>
</div>
</div>
</div>
<div class="table-responsive">
<table id="members_data" class="table table-bordered table-striped">
<thead>
<tr>
<th style="width: 10%">
Employee ID
</th>
<th style="width: 10%">
Role
</th>
<th style="width: 10%">
Region
</th>
<th style="width: 12%">
Org Level1
</th>
<th style="width: 12%">
Org Level2
</th>
</tr>
</thead>
</table>
#endsection
<script type="text/javascript">
$(document).ready(function(){
fill_datable();
function fill_datable(Business_unit = ''){
var datatable = $('members_data').DataTable({
processing: true,
ajax:{
url:{{ "route('CustomSearch.index')" }},
data:{ Business_unit:Business_unit }
},
columns: [
{
data: 'membersid',
name: 'membersid'
},
{
data: 'Role',
name: 'Role'
},
{
data: 'Region',
name: 'Region'
},
{
data: 'Orglevel1',
name: 'Orglevel1'
},
{
data: 'Orglevel2',
name: 'Orglevel2'
},
]
});
}
$('#search').click(function()
{
var Business_unit = $('#Business_unit').val();
if( Business_unit != '')
{
$('#members_data').DataTable().destroy();
fill_datable(Business_unit);
}
else
{
alert('Select Business Unit Filter');
}
});
$('#reset').click(function(){
$('#Business_unit').val();
$('#members_data').DataTable().destroy();
fill_datable();
});
});
</script>
and this is the route
Route::get('/test', [App\Http\Controllers\CustomSearchController::class, 'index'])->name('test');
Not sure what is missing... I am able to load the Business units in dropdown but the data is not loading and nor the filters are getting applied. Can someone help me out in this?

Laravel: how to make pagination when you get json data from controller in javascript?

let's say i have json data coming from my controller, that data is paginated I want display pagination result inside the javascript.
I mean...I want to use the links() method inside javascript but pagination not appearing... is it ok to write it inside javascript or what?.
Here's the data coming from the controller:
Controller
public function getPaginatedData(Request $request)
{
// some data goes here
$output = '';
$data = DB::table('schedules')
->where('station_id', $stations_id)
->paginate(2);
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->id.'</td>
<td>'.$row->schedule_number.'</td>
<td>'.$row->route_name.'</td>
<td>'.$row->user_first.'</td>
<td>'.$row->created_at.'</td>
<td> <a style="margin-left: em; " href="' . url('schedule/' .$row->id .'/edit') . '">
<button style=" font-size: 1em; width: 4.5em; height: 2.5em;" type="button" class="btn btn-success btn-sm">Edit
</button>
</a></td>
<td> <a style="color: white; margin-left: em;" href="javascript:;" data-toggle="modal" onclick="deleteData('.$row->id.')"
data-target="#delete_confirm" class="btn btn-danger">
Delete
</a></td>
</tr>
';
}
$records = array(
'output' => $output,
'schedules' => $data
);
echo json_encode($records);
}
so here what i tried when i get the json from controller in javascript
Javascript
success:function(records)
{
console.log(records.output);
$('tbody').html(records.output);
$('#pager').html(' <ul class="pager">'+ records.schedules.links +'</ul>');
}
View
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Schedule_number</th>
<th>Route</th>
<th>User</th>
<th>Created_at</th>
<th>edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="pager">
</div>
when i run the above code nothing appears... is there any solution to my promblem, guys? thanks!
Instead of sending all the data along with html from controller function, You can just send JSON data. as shown below
$data = DB::table('schedules')
->where('station_id', $stations_id)
->paginate(2);
return $data -> toJson();
This json response will also include your pagination links.
You can use these links in your blade file
I hope it will work

read selected variable and then send back from table to controller

I am having a table with data from database called through codeigniter controller.What I want to do is read the selected value from within the table send it back to the controller and use those values to retrieve new records from DB and then load them on again into the page.
My Controller:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Dashboard1 extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('dash_match_model');
$this->session->keep_flashdata('supplier_id');
$this->load->helper('url');
$this->load->database();
}
public function index() {
$arr['page']='dash1';
$arr['present_all_suppliers'] = $this->dash_match_model->dash_present_all_suppliers();
$arr['supplierCompany'] = "";
$this->load->view('clients/clDashboard',$arr);
}
public function select_supplier() {
$supplierCompany = $this->input ->post('supplierCompany');
$arr['present_all_suppliers'] = $this->dash_match_model->dash_present_all_suppliers();
$arr['supplierCompany'] = $supplierCompany;
$supplier_selected = $this->user_model->return_selected_supplier($supplierCompany);
foreach($supplier_selected->result() as $row)
{
$this->session->set_flashdata('supplier_id', $row->supplier_id);
}
$this->load->view('unspscSegment',$arr);
}
}
Specific lines of table of my view file:
<table id="suppliertable" class="table table-striped table-bordered bootstrap-datatable datatable">
<thead>
<tr>
<th>Supplier</th>
<th>Open Range</th>
<th>Fill Content</th>
<th>Total Match</th>
</tr>
</thead>
<tbody>
<?php foreach ($present_all_suppliers as $v): ?>
<tr>
<td onclick="window.location = 'http://example.com'" class="center" style="color:#0c595b;"> <?php echo $v->supplierCompany; ?> </td>
<td class="center"></td>
<td class="center"></td>
<td class="center"></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
How can I do that with javascript so when i select a supplier (value) to get the selected value and sent it to the controller? Then what should I modify to the controller in order to send the value to the model and collect it and reload them in the view?
You can use jQuery.ajax()
Implemented in your code:
Script:
<script>
$(".supplier_edit").click(function(){
var supplier_company = $(this).find('input').val()
$.ajax({
type: 'POST',
url: 'http://example.com/'+'Dashboard1/select_supplier',
data: {supplierCompany: supplier_company},
success: function(result) {
$("#content").html(result)
}
})
return false
})
</script>
HTML:
<tbody>
<?php foreach ($present_all_suppliers as $v): ?>
<tr>
<td class="supplier_edit" style="color:#0c595b;"><input type="hidden" value="<?php echo $v->supplierCompany; ?>" ></td>
<td class="center"></td>
<td class="center"></td>
<td class="center"></td>
</tr>
<?php endforeach; ?>
</tbody>
<div id="content">content from the controller</div>

Black Holed Request Cakephp

On my index page I have check boxes in each row of my table.
To edit selected items, I use javascript/jquery to grab the class of the checkboxes, build an array of the ids and then post it to the edit selected method in my controller.
Now, this all works perfectly, but when Security in enabled in my App Controller, my post gets black holed and the array is not posted.
Here is my index.ctp file:
<table id="indexTable">
<thead><tr>
<th> <?php echo $this->Form->checkbox('select_all', array('value' => 'select_all')); ?> </th>
<th> <?php echo $this->Paginator->sort('id', 'ID'); ?> </th>
<th> <?php echo $this->Paginator->sort('name', 'Name'); ?> </th>
<th>Auto Offset </th> <th>UTC Offset Sec </th> <th>In Month </th>
<th>In Week </th> <th>In Dow </th> <th>In Hour </th> <th>Out Month </th>
<th>Out Week </th> <th>Out Dow </th> <th>Out Hour </th> <th>Offset Sec </th>
<th>DST Ref </th> <th>Actions </th>
</tr></thead>
<tbody>
<?php
$this->Form->create('LocalClock');
foreach($localClocks as $LocalClock) { ?>
<tr>
<td> <?php echo $this->Form->checkbox('LocalClocks'.$LocalClock['LocalClock']['id'], array('value' => $LocalClock['LocalClock']['id'], 'hiddenField' => false));?> </td>
<td> <?php echo $LocalClock['LocalClock']['id']; ?> </td>
<td> <?php echo $LocalClock['LocalClock']['name']; ?> </td>
<td> <?php echo $LocalClock['LocalClock']['auto_offset']; ?> </td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<!-- This <div> contains all the actions that can be performed on the Local Clocks. -->
<div>
<p>
<span style="float: left">
<?php echo $this->Html->link(__('Edit All Items'), array('action' => 'editAll'), array('class' => 'link'));?>
</span>
<span style="float: left">
<?php echo $this->Html->link(__('Edit Selected Items'), array('action' => 'lceditSelected'), array('class' => 'general_dialog'));?>
</span>
<span style="float: right">
<?php echo $this->Html->link(__('Delete Selected Items'), array('action' => 'deleteSelected'), array('class' => 'general_dialog'));?>
</span>
<?php $this->Form->end(); ?>
</p>
</div>
I took out some unimportant stuff. The problem is with my edit selected and delete selected functions.
Here is the javascript code that waits for their click and then builds the array to post to the controller action:
$('.general_dialog').live('click', function()
{
$.ajaxSetup({ async: false });
var $selDialog = $("#general_dialog").dialog(
{
autoOpen: false,
modal: true,
});
var postInfo = $('#LocalClockIndexForm').serialize();
$.ajax({
url: $(this).attr('href'),
type: "post",
data: postInfo,
success: function (response)
{
alert('success');
},
error: function()
{
alert("failed");
}
});
$selDialog.load($(this).attr('href'), function ()
{
$selDialog.dialog('open');
});
return false; // Ensure the controller does not redirect to the actual edit page
});
Any help on how to get it to work without getting black holed would be greatly appreciated.
Thanks in advance
------------------------------------------EDIT----------------------------------------------
I added $this->Form->create('LocalClock') and $this->Form->end() to the table and I switched the $.post() to and $.ajax() call.
If I send the serialised form, I don't get a black hole, but when I look at the data posted, it does not include any of the check box ids.
Your example lacks form tags.
You need to create and end the form with the Form helper to ensure that the security token is included in the form generation:
$this->Form->create();
// Other form elements here.
$this->Form->end();
Have you tried to modify crsf protection policy?
If you reload the page with the same token, the Security component will black hole the request.
var $components = array('Security'=>array('csrfUseOnce'=>false));

Categories