How can I use searchbar using ajax in laravel? - ajax

In laravel, I am using search bar in list view, It will search from the record using ajax and display me the output.
But it's now working, when i write any text in search bar I didn't get any output. All records displays as it is.
My database in mongoDb, and i am coding in laravel.
Here is my view file code.
view
<div class="table-responsive m-t-40">
<div class="form-group">
<input type="text" name="search" id="search" class="form-control" placeholder="Search Department" />
</div>
<table class="table table-bordered table-striped ">
<thead>
<tr>
<th>Department Name</th>
<th>Created By</th>
<th>Created On</th>
#if (App\User::isPermitted(['edit_department', 'update_department', 'delete_department']))
<th>Action</th>
#endif
</tr>
</thead>
<tbody>
#if($listOfDepartment != null)
#foreach($listOfDepartment as $departmentList)
<tr>
<td>{{$departmentList->nameOfDepartment}}</td>
<td>{{$departmentList->createdBy}}</td>
<td>{{$departmentList->created_at}}</td>
#if (App\User::isPermitted(['edit_department', 'update_department', 'delete_department']))
<td>
<i class="fa fa-edit fa-lg" style="color:#0066ff" aria-hidden="true"></i> 
<i class="fa fa-trash fa-lg" onclick="delete_user(this); return false;" style="color:red" aria-hidden="true"></i>
</td>
#endif
</tr>
#endforeach
#endif
</tbody>
</table>
</div>
script
<script>
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('list_department') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query);
});
});
</script>
and here is my code of controller file
namespace App\Http\Controllers;
use App\Department;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
public function listDepartment(Request $request)
{
$listOfDepartment = Department::all();
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = Schema::table('department')
->where('nameOfDepartment', 'like', '%'.$query.'%')
->orWhere('createdBy', 'like', '%'.$query.'%')
->get();
}
else
{
$data = Schema::table('department')
->orderBy('nameOfDepartment', 'asc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '<tr>
<td>'.$row->nameOfDepartment.'</td>
<td>'.$row->createdBy.'</td>
</tr>';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
return view('pages.department', compact('listOfDepartment'));
}

Related

how to implement Laravel AJAX live search on CRUD management table?

I have a CRUD table that's holding records of doctors that get
retrieved from the MySQL database. I've been following a few tutorials
and managed to set up AJAX live results search.
Now the problem comes from the fact that the logic is stored in a
Controller. I can succesfully retrieve the details from the database
using '-- foreach($data as $row) --' but I don't know how to retrieve
the CRUD actions ( In this case Delete.The create method is separated
from the table itself. I also can't implement status cell using i)
I've tried putting the actions inside the td'. .'td. tags but I get
Routing errors.
Any help is appreciated.
I have the code for the CRUD actions, images etc..inside
"index.blade.php". They should be somehow implemented in the
controller though. doctor controller
function liveSearchDoctor(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data =Doctor::
where('name', 'like', '%'.$query.'%')
->orWhere('mobile', 'like', '%'.$query.'%')
->orWhere('email', 'like', '%'.$query.'%')
->orderBy('id', 'desc')
->paginate(2);
}
else
{
$data =Doctor::latest()->paginate(2);
}
$total_data = $data->count();
if($total_data > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td class="center"><img src="'.$row->image.'" style="width:40px;height:40px;"/></td>
<td>'.$row->id.'</td>
<td>'.$row->name.'</td>
<td>'.$row->department->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->mobile.'</td>
//status should be implement here
<td><a class="btn btn-primary" href="'.route('doctors.edit',$row->id).'"><i class="fas fa-edit">Edit</i></a>
//delete form should be implement here
</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_data
);
echo json_encode($data);
}
}
index.blade.php (( Note: The CRUD actions and everything is here
implemented succesfully. I however can't implement delete in the
controller )) here is the index.blade.php
#extends('layout.master')
#section('css')
#endsection
#section('content')
<br>
<div class="br-pagebody">
<div class="br-section-wrapper">
#include('include._message')
<div class="row">
<h6 class="br-section-label">Doctors List</h6>
</div>
<div class="row">
<div class="col-lg-4 ">
<div class="form-group">
<input type="text" name="search" id="search" class="form-control" placeholder="Search doctor Data" />
</div>
</div>
<div class="col-lg-3 offset-lg-5">
Add New Doctor
</div>
</div>
</br>
<div class="table-responsive">
<table class="table table-bordered table-colored table-dark">
<thead class="thead-colored thead-dark">
<tr>
<th>Image</th>
<th>Doctor Id</th>
<th>Name</th>
<th>Department</th>
<th>Email</th>
<th>mobile</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#foreach($doctors as $doctor)
<tr>
<td class="center"><img src="{{URL::asset($doctor->image)}}" style="width:40px;height:40px;"/></td>
<td class="center">{{$doctor->id}}</td>
<td class="center">{{$doctor->name}}</td>
<td class="center">{{$doctor->department->name}}</td>
<td class="center">{{$doctor->email}}</td>
<td class="center">{{$doctor->mobile}}</td>
<td class="center">
#if($doctor->status==1)
<span class="badge badge-success">Active</span>
#else
<span class="label label-danger">Deactive</span>
#endif
</td>
<td class="center">
<a class="btn btn-primary" href="{{route('doctors.edit',$doctor->id)}}">
<i class="fas fa-edit">Edit</i>
</a>
{!! Form::open(['method' => 'DELETE','route' => ['doctors.destroy', $doctor->id],'style'=>'display:inline']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
</tbody>
</table>
</div><!-- table-wrapper -->
<div class="d-flex justify-content-center">
{!! $doctors->links() !!}
</div>
</div>
</div>
#endsection
#section('js')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
fetch_doctor_data();
function fetch_doctor_data(query = '')
{
console.log(query)
$.ajax({
url:"{{route('search.doctor')}}",
method:"GET",
data:{'query':query},
dataType:'json',
success:function(data)
{
console.log(data)
$('tbody').html(data.table_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_doctor_data(query);
});
});
</script>
#endsection

Use button inside controller

I am trying to search users in a panel with ajax. But along with that, I also want to edit the selected user.
I have created the button inside the controller to achieve this but the button isn't working.
Here is my controller code:
public function searchTeacher(Request $request){
if($request->ajax()){
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('users')->where('name', $query)->get();
}else{
$data = DB::table('users')->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->teacherId.'</td>
<td>'.$row->subject.'</td>
<td> <button href={{route(update-teacher-view), '.$row->id.'}}> Edit</button> </td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
}
Here is the ajax for search method-
<script>
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
console.log(query)
$.ajax({
url:"{{ route('search-teacher') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query);
});
});
Here is my html-
<section class="panel">
<table class="table table-striped">
<thead class="team-list chat-list-side info border-less-list">
<th>Teacher Name</th>
<th>Email</th>
<th>Teacher Id</th>
<th>Subject</th>
</thead>
<tbody>
</tbody>
</table>
</section>
A solution will be appreciated.
Thanks in advance.
Maybe it's a wrong string interpolation? Should be like this:
<?php
$output .= '
<tr>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->teacherId.'</td>
<td>'.$row->subject.'</td>
<td> <button href='.route('update-teacher-view', $row->id).'> Edit</button> </td>
</tr>
';
Also instead of echo-ing, just return the value, it will be automatically converted to JSON response:
// echo json_encode($data); // Change this line to below
return $data;
Render the blade file with the data this is the best solution.
In controller
return View::make('ajaxFilter',compact('data'))->render();
On ajaxFilter.blade.php
<section class="panel">
<table class="table table-striped">
<thead class="team-list chat-list-side info border-less-list">
<th>Teacher Name</th>
<th>Email</th>
<th>Teacher Id</th>
<th>Subject</th>
</thead>
<tbody>
#if($data->count() > 0)
#foreach($data as $row)
<tr>
<td>{{ $row->name }}</td>
<td>{{ $row->email }}</td>
<td>{{ $row->teacherId }}</td>
<td>{{ $row->subject }}</td>
<td>
Edit //button design
</td>
</tr>
#endforeach
#else
No data Found
#endif
</tbody>
</table>
</section>
On ajax response, you can append HTML data something like that
$('#div_or_section_id').html(data);

Call to a member function links() on array in Laravel

I am receiving this error while trying to create pagination in laravel.
ErrorException in 1e886a45102a3e4898f23b52cd7ca771 line 396: Call to a
member function links() on array (View:
C:\xampp\htdocs\soulfy_repo\framework\resources\views\soulfy\setting.blade.php)
line 396: <?php echo e($themes->links()); ?>
HomeController.php
public function getBackgroundTheme()
{
$query = DB::table('theme_background');
if (request()->has('menu')) {
$theme = DB::table('kategori_name')->where('kategori_theme', request('menu'))->first();
$query = $query->where('kategori_id', $theme->kategori_id);
}
//$model = $query->get();
$theme = $query->paginate(4);
return view('soulfy.setting', [
'themes'=>$theme,
'user' => auth()->user(),
]);
// return redirect('/home/setting' .
}
setting.blade.php
<table>
#if(isset($themes))
#foreach($themes as $m)
<tr>
<td><img width="100px" height="100px" src="{{url('/')}}/uploads/theme/{{$m->pic_name}}.jpg"/></td>
<td><img width="100px" height="100px" src="{{url('/')}}/uploads/theme/{{$m->pic_name}}.jpg"/></td>
<td><img width="100px" height="100px" src="{{url('/')}}/uploads/theme/{{$m->pic_name}}.jpg"/></td>
</tr>
<tr>
<td><div class="box"><input type="checkbox" name="pic" value=""></div></td>
<td><input type="checkbox" name="pic" value=""></td>
<td><input type="checkbox" name="pic" value=""></td>
</tr>
#endforeach
{{ $themes->links() }}
#endif
</table>
$theme = DB::table('kategori_name')->where('kategori_theme', request('menu'))->paginate(PAGELIMIT);
Use This In Your Home Controller. Instead Of first();
And Define This In Your Routes : define('PAGELIMIT','4');

ajax delete using codeigniter

Hi i have this delete thing, and im using it on ajax to delete the data. My problem is it wont delete on the database, when i refresh the browser the data remains, Can someone help me out figured this thing??
Here's my controller below
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start();
class News_and_events extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->model('admin_model', 'am');
}
public function index(){
if($this->session->userdata('logged_in')){
$this->data['title'] = 'News and Events | Spring Rain Global Consultancy Inc Admin Panel';
$this->data['logout'] = 'Logout';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->data['allData'] = $this->am->getAllData();
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/news_and_events', $this->data);
$this->load->view('pages/admin_footer');
}else{
redirect('login', 'refresh');
}
}
public function add(){
if($this->session->userdata('logged_in')){
$this->form_validation->set_rules('date', 'Date', 'trim|required|xss_clean');
$this->form_validation->set_rules('event', 'Event', 'trim|required|xss_clean');
$this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean');
if($this->form_validation->run() == FALSE){
$this->data['title'] = 'News and Events | Spring Rain Global Consultancy Inc Admin Panel';
$this->data['logout'] = 'Logout';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->data['allData'] = $this->am->getAllData();
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/news_and_events', $this->data);
$this->load->view('pages/admin_footer');
}else{
$array = array(
'Date' => $this->input->post('date'),
'Event' => $this->input->post('event'),
'Description' => $this->input->post('description')
);
$this->am->saveData($array);
$this->session->set_flashdata('add_another',1);
redirect('news_and_events', 'refresh');
}
}else{
redirect('homepage', 'refresh');
}
}
public function delete(){
$id = $this->uri->segment(2);
$this->am->delete($id);
redirect(base_url().'news-and-events');
}
}
and my views
<script type="text/javascript">
$(document).ready(function(){
$("#add_another").click(function(){
});
});
function goDelete(id){
var agree = confirm("Are you sure you want to delete this?");
if(agree){
$("#news-and-event"+id).fadeOut('slow');
$.post('<?php echo base_url().'news-and-events/delete/'?>', {id:id}, function(){
});
}else{
return false;
}
}
</script>
<div class="container" >
<br />
<br />
<br />
<ul id="nav">
<li><h4>Home</h4></li>
<li><h4>News and Events</h4></li>
<li><h4>Activities</h4></li>
</ul>
<div class="starter-template">
<h1>News And Events</h1>
<?php if(!$this->session->flashdata('add_another')):?>
<form action="<?php echo base_url().'news-and-events/add'?>" method="post">
<?php echo validation_errors('<div class="error">', '</div>');?>
<table class="table-striped">
<tr>
<td>Date: </td>
<td><input type="text" id="datepicker" name="date" value="<?php echo set_value('date');?>" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td >Event: </td>
<td ><input type="text" name="event" value="<?php echo set_value('event');?>" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td width="20%">Description: </td>
<td><textarea cols="30" rows="5" name="description" ><?php echo set_value('description');?></textarea></td>
</tr>
<tr>
<td width="20%"> </td>
<td><input type="submit" value="Add" class="btn btn-success" /></td>
</tr>
</table>
</form>
<?php else: ?>
<div id="add_another" style="float:left;">
<input type="button" value="Add Another" class="btn btn-primary" />
</div>
<?php endif; ?>
<br />
<br />
<table class="table" >
<tr>
<th>Date</th>
<th width="47%" >Event</th>
<th width="32%">Description</th>
<th>Options</th>
</tr>
<?php foreach($allData as $x => $allDatas): ?>
<tr id="news-and-event<?php echo $allDatas->id; ?>">
<td width="10%"><?php echo $allDatas->Date; ?></td>
<td style="text-align:left;"><?php echo $allDatas->Event; ?></td>
<td style="text-align:left;"><?php echo $allDatas->Description; ?></td>
<td width="10%">
Edit |
<a href="javascript:;" onclick="return goDelete('<?php echo $allDatas->id;?>');" >Delete</a>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div><!-- /.container -->
<script>
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('#datepicker').datepicker({
minDate: new Date(currentYear, currentMonth, currentDate),
dateFormat: "yy-mm-dd"
});
</script>
and my model to delete the database
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Admin_model extends CI_Model{
public function saveData($array){
$this->db->insert('news_and_updates', $array);
}
public function getAllData(){
return $this->db->order_by("Date", "desc")
->get('news_and_updates')
->result_object();
}
public function delete($id){
$this->db->where('id', $id)->delete('news_and_updates');
}
}
?>
im using the $this->uri->segment(2); any help? is much greatly appreciated
thanks
You are sending data via POST but you are trying to delete based on the uri segment.
Try this instead in your controller:
public function delete(){
$id = $this->input->post('id');
$this->am->delete($id);
redirect(base_url().'news-and-events');
}

Error update row in codeignaitor

i have error when i update row to database.
my problem is not update the row and call me when i upload pic with update the file upload not define in index.
my controller :
public function addedit(){
$events = new events_model();
$prodID = $this->input->post('hID');
$text = $this->input->post('ev_text');
$pic = $this->do_upload('ev_pic');
$submit = $this->input->post('submit');
if($submit){
if(!empty($prodID)){
$this->data['events'] = $events->UpdatePost($prodID, $text , $pic );
$this->data['pagetitle'] = "Show Info";
$this->data['success']= "Update Done";
}else{
$this->data['success'] = "Add Done";
}
$this->data['status'] = "1";
}else{
$this->data['status'] = "0";
$this->data['errors'] = "Error";
}
$this->template->build('admin/events/add',$this->data);
}
and model :
function UpdatePost($prodID, $text , $pic ) {
if ($pic == ""){
$vales = array('ev_id' => $prodID , 'ev_text' => $text);
}else{
$vales = array('ev_id' => $prodID , 'ev_text' => $text , 'ev_pic' => $pic);
}
$query = $this->db->update($this->table_name, $vales) or die (mysql_error());
$result = array();
$result["process"] = "ok";
echo "1";
}
and view :
<div class="widget-body">
<table class="data-table" action="./administrator/categories/delete/"><!-- Table Conversion: See Section E in custom.js -->
<thead>
<tr>
<th class="sorting no-background" rowspan="1" colspan="1" style="width: 35px;"><input type="checkbox" id="checkall" /></th>
<th class="sorting" rowspan="1" colspan="1" style="width: 343px;">Tittle</th>
<th class="sorting" rowspan="1" colspan="1" style="width: 100px;">Date</th>
<th class="sorting no-background" rowspan="1" colspan="1" style="width: 70px;">#</th>
</tr>
</thead>
<tbody>
<?php $ctr = 0; ?>
<?php foreach ($events as $n): ?>
<tr>
<td><input class="checkrow" type="checkbox" value="<?php echo $n->ev_id; ?>" /></td>
<td class=" sorting_1"><?= $n->ev_text; ?></td>
<td class="center"><?= $n->ev_date; ?></td>
<td>
<span>Edit</span>
<span>Del</span>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<div id="table-extra">
<div id="table-action">
<input action="./administrator/<?php echo $this->uri->segment(2)."/deleteitems" ?>" class="btn-theme table-button btn-hover-black DeleteItems" id="submit" type="button" value="Delete" />
</div>
<div class="paginate">
<ul>
<?= $this->pagination->create_links(); ?>
</ul>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
where problem in my code , and i wont to update success.
you don't load models like this $events = new events_model(); in CI, you should do it like this :
$this->load->model('Model_name');
$this->Model_name->function();
ref : http://ellislab.com/codeigniter/user-guide/general/models.html#loading

Resources