I'm trying to fetch blogs using AJAX function in Laravel. But it is not working, neither showing any error. What I want is to display a load more button from where more blogs will be loaded using AJAX request. Here is my front-end code:
<div class="panel-body">
{{ csrf_field() }}
<div id="post_data"></div>
</div>
And my ajax script:
$(document).ready(function(){
var _token = $('input[name="_token"]').val();
load_data('', _token);
function load_data(id="", _token)
{
$.ajax({
url:"{{ route('loadmore.load_data') }}",
method:"POST",
data:{id:id, _token:_token},
success:function(data)
{
$('#load_more_button').remove();
$('#post_data').append(data);
}
})
}
$(document).on('click', '#load_more_button', function(){
var id = $(this).data('id');
$('#load_more_button').html('<b>Loading...</b>');
load_data(id, _token);
});
});
Here is my route:
web.php
Route::post('/loadmore', 'LoadMoreController#load_data')->name('loadmore.load_data');
Here is the controller function:
LoadMoreController.php
class LoadMoreController extends Controller
{
public function load_more(){
function load_data(Request $request)
{
if($request->ajax())
{
if($request->id > 0)
{
$data = DB::table('blogs')
->where('blog_id', '<', $request->id)
->orderBy('blog_id', 'DESC')
->limit(6)
->get();
}
else
{
$data = DB::table('blogs')
->orderBy('blog_id', 'DESC')
->limit(6)
->get();
}
$output = '';
$last_id = '';
if(!$data->isEmpty())
{
foreach($data as $row)
{
$output .= '
<div class="row">
<div class="col-md-12">
<h3 class="text-info"><b>'.$row->blog_title.'</b></h3>
<p>'.$row->blog_content.'</p>
<br />
<br />
<hr />
</div>
</div>
';
$last_id = $row->id;
}
$output .= '
<div id="load_more">
<button type="button" name="load_more_button" class="btn btn-success form-control" data-id="'.$last_id.'" id="load_more_button">Load More</button>
</div>
';
}
else
{
$output .= '
<div id="load_more">
<button type="button" name="load_more_button" class="btn btn-info form-control">No Data Found</button>
</div>
';
}
echo $output;
}
}
}
}
I'll be happy to provide any other details if needed or asked. Any suggestions/solutions will be highly appreciated.
Laravel version 8
web.php
Here is route file below:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/loadmore', [App\Http\Controllers\LoadMoreController::class, 'index']);
Route::post('/loadmore/load_data', [App\Http\Controllers\LoadMoreController::class, 'load_data'])->name('loadmore.load_data');
Related
So when I put a route name with a single parameter it works flawlessly but when I pass named route with two parameters I get a 500 error in my console which looks like this:GET http://127.0.0.1:8000/admin/packages/package-programs/kathmandu/action?query= 500 (Internal Server Error).
<?php
namespace App\Http\Controllers\AdminVisible;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Program;
use App\Package;
use DB;
class PackageProgramController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index($packageSlug)
{
$showCounts = Program::count();
$packages = Package::firstOrFail();
return view('admin.pages.packageprogram',compact('showCounts','packageSlug','packages'));
}
function action($packageSlug,Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('programs')
->where('id', 'like', '%'.$query.'%')
->orWhere('day', 'like', '%'.$query.'%')
->orWhere('Package_Type', 'like', '%'.$query.'%')
->orWhere('title', 'like', '%'.$query.'%')
->orderBy('id', 'desc')
->get();
}
else
{
$data = DB::table('programs')
->orderBy('id', 'desc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$packageProgram = ['packageProgram' => $row->id];
$route = route('PackageProgram.edit',['packageSlug' => $packageSlug, 'packageProgram' => $packageProgram]);
$output .= '
<tr>
<th scope="row"><input type="checkbox" name="ids[]" class="selectbox" value="'.$row->id.'" onchange="change()"></th>
<td onClick="location.href=\''.$route.'\' " style="cursor: pointer">'.$row->id.'</td>
<td onClick="location.href=\''.$route.'\' " style="cursor: pointer">'.$row->day.'</td>
<td onClick="location.href=\''.$route.'\' " style="cursor: pointer">'.$row->title.'</td>
<td onClick="location.href=\''.$route.'\' " style="cursor: pointer">'.$row->description.'</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="12">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
}
public function create($packageSlug, Package $package)
{
return view('admin.create.createPackageProgram',compact('packageSlug','package'));
}
public function store($packageSlug,Request $request)
{
$packages = Package::where('slug', $packageSlug)->firstOrFail();
$data = request()->validate([
'day' => 'required',
'title' => 'required',
'description' => 'required',
]);
$packages->program()->create($data);
switch ($request->input('action')) {
case 'preview':
return redirect()->intended(route('PackageProgram',$packageSlug))->with('message', 'Package Program has been added.');
break;
default:
return redirect()->back()->with('message', 'Package Program has been added.');
break;
}
}
public function edit($packageSlug,Program $packageProgram,Package $package)
{
return view('admin.edit.editPackageProgram',compact('packageSlug','packageProgram','package'));
}
public function update($packageSlug, Program $packageProgram)
{
$data = request()->validate([
'day' => 'required',
'title' => 'required',
'description' => 'required',
]);
$packageProgram->update($data);
return redirect()->intended(route('PackageProgram',$packageSlug))->with('message', 'Package Program has been updated.');
}
public function delete(Request $request) {
$data = request()->validate([
'deleteSelected' => 'required',
]);
$id = $request->get('ids');
$data = DB::delete('delete from programs where id in ('.implode(",",$id).')');
return redirect()->back()->with('message', 'Testimony has been deleted.');
}
}
My blade file looks something like this:
#extends('layouts.app')
#section('style')
<link href="{{ asset('css/Admin/sql-data-viewer.css') }}" rel="stylesheet">
<style></style>
#endsection
#section('content')
<section class="data-viewer">
<div class="d-flex justify-content-between px-3">
<h3 class="text-white">Select {{$package->Package_Name}} {{$package->Package_Type}} Days to change</h3>
<button type="button" class="btn add-data text-white rounded-pill">Add Day <i class="fas fa-plus"></i></button>
</div>
<form>
#csrf
#method('DELETE')
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
<div class="d-flex justify-content-between selectDelete">
<div class="delete pl-3 mt-3 mb-3">
<label for="deleteSelected">Action:</label>
<select name="deleteSelected" id="deleteSelected" class="#error('deleteSelected') is-invalid #enderror" name="deleteSelected" >
<option disabled selected>---------</option>
<option>Delete Selected Package Program</option>
</select>
<button formaction="{{ route('PackageProgram.delete',$package) }}" formmethod="POST" type="submit" class="go" id="deleleGo" onclick="deleteBtn()">Go</button>
<span id="selected">0</span> of {{$showCounts}} selected
#error('deleteSelected')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<strong id="selectError">You must check at least one checkbox</strong>
</div>
<div class="search pr-3 mt-3 mb-3">
<label for="search">Search:</label>
<input id="search" type="text" color="#000" class="rounded #error('search') is-invalid #enderror" name="search" value="{{ old('search') }}" autocomplete="search" placeholder="Search">
#error('search')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<table class="table table-hover table-striped table-dark">
<thead>
<tr>
<th scope="col"><input type="checkbox" id="checkHead" class="selectall"></th>
<th scope="col">Id</th>
<th scope="col">Day</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody></tbody>
</table>
</form>
</section>
#endsection
#section('script')
<script src="{{ asset('/js/sqlData.js') }}"></script>
<script>
$(document).ready(function(){
fetch_data();
function fetch_data(query = '')
{
$.ajax({
url:"{{ route('PackageProgram.action',$packageSlug) }}",
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_data(query);
});
});
function checkboxError(){
var number = document.querySelectorAll('.selectbox:checked').length;
if(number == 0) {
var a = document.getElementById("selectError").style.display = "block";
return false;
}
}
window.addEventListener('DOMContentLoaded', (event) => {
var deleteBtn = document.getElementById("deleleGo");
deleteBtn.onclick = checkboxError;
});
</script>
#endsection
So my route file looks something like this:
Route::prefix('package-programs')->group(function() {
Route::get('/', 'AdminVisible\packagePackageProgramController#index')->name('PackagePrograms');
Route::get('/action', 'AdminVisible\packagePackageProgramController#action')->name('PackagePrograms.action');
Route::prefix('{packageSlug}')->group(function() {
Route::get('/', 'AdminVisible\PackageProgramController#index')->name('PackageProgram');
Route::get('/action', 'AdminVisible\PackageProgramController#action')->name('PackageProgram.action');
Route::get('/create', 'AdminVisible\PackageProgramController#create')->name('PackageProgram.create');
Route::post('/create', 'AdminVisible\PackageProgramController#store')->name('PackageProgram.store');
Route::delete('/delete','AdminVisible\PackageProgramController#delete')->name('PackageProgram.delete');
Route::get('/{packageProgram}/edit', 'AdminVisible\PackageProgramController#edit')->name('PackageProgram.edit');
Route::patch('/{packageProgram}', 'AdminVisible\PackageProgramController#update')->name('PackageProgram.update');
});
});
It might be I do not know how to pass named route with two parameters but in my blade file, I been doing it like this, and there it works. Is it something different that must be done in the controller.
First start from blade (please check comments):
#extends('layout')
#section('content')
<div class="row">
<table class="table table-hover table-striped table-dark" id="slugTb">
<thead>
<tr>
<th scope="col"><input type="checkbox" id="checkHead" class="selectall"></th>
<th scope="col">Id</th>
<th scope="col">Day</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function() {
var query = 'damnSon';
$.ajax({
url: "{{ route('test.action') }}",
method: 'GET',
data: {
'slug': '{{ $packageSlug }}',
'query': query
},
dataType: 'json',
})
.done(function(data) {
console.log(data) //use console.log to debug
$('#slugTb tbody').html(data.table_data); //set table id so that you don't miss the right one
})
.fail(function(err) {
console.log(err) //in case if error happens
})
.always(function() {
console.log( "complete" ); //result despite the response code
});
});
</script>
#endsection
You used deprecated jquery method like success check
Better use this three: done,fail,always
Next route web.php:
Route::get('action', ['as' => 'test.action', 'uses' => 'TestController#action']);
In your case better to use Request params bag so that you can add as much params as you want.
Next controller:
function action(Request $request)
{
$total_row = 1;
$packageSlug = $request->get('slug'); //names that you set in ajax data tag: {'slug': '{{ $packageSlug }}','query': query}
$query = $request->get('query');
$output = '<tr>
<td align="center" colspan="1">' . $packageSlug . '</td>
<td align="center" colspan="1">' . $query .'</td>
</tr>';
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
return response()->json($data);
}
You should return something from the controller so blade can show that data and json encode it so that js could parse it. That is why return response()->json($data);
Other way:
route:
Route::get('/action/{slug}/{query}',['as' => 'test.action', 'uses' => 'TestController#action']);
blade script:
<script>
$(document).ready(function() {
var query = 'damnSon';
$.ajax({
url: 'action/{{ $packageSlug }}/' + query,
method: 'GET',
dataType: 'json',
})
.done(function(data) {
console.log(data) //use console.log to debug
$('#slugTb tbody').html(data.table_data); //set table id so that you don't miss the right one
})
.fail(function(err) {
console.log(err) //in case if error happens
})
.always(function() {
console.log( "complete" ); //result despite the response code
});
});
</script>
and controller:
function action($slug, $query)
{
$total_row = 1;
$packageSlug = $slug;
$query = $query;
$output = '<tr>
<td align="center" colspan="1">' . $packageSlug . '</td>
<td align="center" colspan="1">' . $query .'</td>
</tr>';
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
return response()->json($data);
}
Not recommended just because you manually type route in ajax request: url: 'action/{{ $packageSlug }}/' + query if your route changes you have to change it in js.
I am working on old laravel project and I have to modify existing one. So I am now trying to understand the code. The project is on laravel and yajra datatable. I can't understand how the destroy function work ? In the view there is a no call for destroy function but when I click the delete button still it is working.
Controller
public function loadSizes()
{
$sizes = Size::select(['id', 'name', 'code'])->get();
return DataTables::of($sizes)
->addColumn('action', function ($size) {
return '<i class="fa fa-wrench" aria-hidden="true"></i>
<button type="button" data-id="' . $size->id . '" class="btn btn-default remove-size remove-btn" data-toggle="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt" aria-hidden="true"></i></button>';
})
->rawColumns(['action'])
->make(true);
}
public function destory(Request $request)
{
$result = Size::where('id', $request->input('size_id'))->delete();
if ($result) {
return "SUCCESS";
} else {
return "FAIL";
}
}
view
#extends('layouts.sidebar')
#section('content')
<div class="row">
<div class="col-sm-12 pad-main">
<div class="row">
<div class="col-md-6">
<h4 class="cat-name"> Size List</h4>
</div>
</div>
<div class="row">
<div class="col-md-12 table-responsive pad-tbl">
<table class="table table-striped" id="size_table">
<thead>
<tr>
<th scope="col"> Name</th>
<th scope="col"> Code</th>
<th scope="col"> Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
#if (Session::has('action'))
#if (Session::get('action') == "create")
#if (Session::has('status_success'))
<script > showAlert("SUCCESS", "Size creation successful");</script >
#elseif(Session::has('status_error')))
<script > showAlert("FAIL", "Size creation fail");</script >
#endif
#elseif(Session::get('action') == "update")
#if (Session::has('status_success'))
<script > showAlert("SUCCESS", "Size update successful");</script >
#elseif(Session::has('status_error')))
<script > showAlert("FAIL", "Size update fail");</script >
#endif
#endif
#endif
<script>
$(document).ready(function () {
$('#size_table').DataTable({
language: {
searchPlaceholder: "Search records"
},
"columnDefs": [
{"className": "dt-center", "targets": "_all"}
],
processing: true,
serverSide: true,
ajax: '{!! url(' / load - sizes') !!}',
columns: [
{data: 'name', name: 'name'},
{data: 'code', name: 'code'},
{data: 'action', name: 'action'},
]
});
});
$(document.body).on("click", ".remove-size", function () {
var size_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Size ?", "deleteSize(" + size_id + ")");
});
function deleteSize(id) {
$.ajax({
type: 'get',
url: '{!! url('delete-size') !!}',
data: {size_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS", "Delete Size successful");
}
}, error: function (data) {
showAlert("FAIL", "Delete Size fail");
}
});
}
</script>
#endsection
At the bottom of the blade view there is an AJAX in function destory(id).
That AJAX is sending a GET request to a URL delete-size with size id.
Now, if you search your web.php file for that URL (location - routes/web.php), you'll find something like this:
Route::get('delete-size', 'SizeController#destory');
This route would be sending the size id to your destory function, which is in turn searching the Size in your DB and deleting it.
// Controller
public function destroy($id)
{
Tag::find($id)->delete();
Toastr::success('Tag Successfully Deleted',"Success");
return redirect()->back();
}
// Route
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){
Route::resource('tag','TagController');
});
// HTML file
<form id="delete-form-{{ $tag->id }}" action="{{ route('admin.tag.destroy',$tag->id) }}" method="POST" style="display: none;">
#csrf
#method('DELETE')
</form>
In presented controller, it's displaying all the users and his attributes(?) such as name, surname, phone and roles. How do I make it that when I select role in checkbox and press "potvrdi"(submit) it submits to database? Do I have to use jquery, ajax?
Thank you
Controller
public function action(Request $request)
{
if ($request->ajax()) {
$query = $request->get('query');
if ($query != '') {
$data = User::where('surname', 'like', '%'.$query.'%')
->orWhere('name', 'like', '%'.$query.'%')
->orWhere('phone', 'like', '%'.$query.'%')
->orderBy('id')
->get();
} else {
$data = User::orderBy('id')
->get();
}
return json_encode($this->generateUserTable($data));
}
}
public function generateUserTable($data)
{
$total_row = $data->count();
$output = "";
if ($total_row > 0) {
foreach ($data as $row) {
$roleNames = '';
$userRoles = $row->roles()->pluck('id')->toArray();
// var_dump($userRoles);
$checked = '';
foreach (Role::all() as $roles1) {
if (in_array($roles1->id, $userRoles)) {
$checked = 'checked="checked"';
}
$roleNames .= $roles1->role != null ? $roles1->role.' '.'<input type="checkbox" '.$checked.' name="role" value="'.$roles1->id.'" class="checkbox" id="checkboxId">'.' ' : '';
}
$output .= '
<tr>
<td>'.$row->surname.'</td>
<td>'.$row->name.'</td>
<td>'.$row->phone.'</td>
<td>'.$roleNames.'</td>
<td><button type="button" id="potvrdi" class="potvrdi-button btn btn-primary" data-id="'.$row->id.'">
<div class="potvrdi">Potvrdi</div>
</button></td>
<td><button type="button" id="rowId" class="remove-button btn btn-danger" data-id="'.$row->id.'">
<div class="close">x</div>
</button></td>
</tr>
';
}
} else {
$output = '
<tr>
<td align="center" colspan="5">Nema podataka</td>
</tr>
';
}
return array(
'table_data' => $output,
'total_data' => $total_row,
);
}
EDIT:
part of html is in controller after $output in generateUserTable
view with js
<!-- Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<h2>{{ $modal }}</h2>
</div>
<div class="modal-footer">
<button type="button" class="rem-mod btn btn-secondary" data-dismiss="modal">Zatvori</button>
<button type="button" class="bck-mod test btn btn-danger" data-dismiss="modal">Obriši korisnika</button>
</div>
</div>
</div>
</div>
<!-- users and search bar -->
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Pretraži korisnike</div>
<div class="panel-body">
<div class="form-group">
<input type="text" name="search" id="search" class="form-control" placeholder="Pretraži korisnike" />
</div>
<div class="table-responsive">
<h3 align="center">Broj korisnika: <span id="total_records"></span></h3>
<table id="users" class="table table-striped table-bordered">
<thead>
<tr>
<th>Prezime</th>
<th>Ime</th>
<th>Telefon</th>
<th>Rola</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
Gets data from database
<script>
$(document).ready(function(){
fetch_user_data();
function fetch_user_data(query = ''){
$.ajax({
url:"{{ route('live_search.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
$(document).on('click', '.potvrdi-button', function(){
post_user_role();
var id = $(this).data('id');
function post_user_role(id){
$.ajax({
url:"{{ route('live_search.action') }}",
method:"GET",
data:{id:id},
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_user_data(query);
});
Modal js
$('#users').on('click', '.remove-button', function(){
var id = $(this).data('id');
$(".test").attr('data-id', id);
$("#deleteModal").modal("show");
});
$(document).on('click', '.bck-mod', function(){
var id = $(this).data('id');
$.ajax({
//url:"{{ route('live_search.destroy') }}",
url:"/live_search/destroy",
method:"get",
data:{id:id},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
},
error: function(data)
{
console.log(data);
}
})
});
});
</script>
I prepared sample fiddle for you. I used dummy values for your users table, also I used select instead of checkbox, but you should follow the same approach.
$(document).on('click', '.potvrdi-button', function(e) {
var value = $(this).closest('tr').find('select[name="role"]').val();
$.ajax({
url: "{{ route('live_search.action') }}",
method: "GET",
data: {
value: value
},
dataType: 'json',
success: function(data) {
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
})
Check your method. Right now it's a GET. You probably want it to be a POST. Check your laravel router to make sure its responding to the POST method.
Guys I just created like/dislike buttons for every service! so I set a default grey color for each one of them, once the user click " like" it turns to green and for the opposite case it turns to red..
so I've created an ajax method for that...
I wanted to check if everything works fine with a simple alert()
but I got an error which is :
message: "Undefined property: Illuminate\Database\Eloquen\Builder::$like",…}
exception : "ErrorException"
— file : "C:\xampp\htdocs\dawerelzirou\app\Http\Controllers\ServiceController.php"
— line:164
message: "Undefined property: Illuminate\Database\Eloquent\Builder::$like"
trace : [
— { file: "C:\xampp\htdocs\dawerelzirou\app\Http\Controller\ServiceController.php", line: 164 }
]
This is like.js
$('.like').on('click', function() {
var like_s = $(this).attr('data-like');
var service_id = $(this).attr('data-serviceid');
$.ajax({
type: 'POST',
url: url,
data: {
like_s: like_s,
service_id: service_id,
_token: token
},
success: function(data) {
alert('ok');
}
});
});
This is the script:
<script type="text/javascript" src="{{ asset('js/like.js') }}"></script>
<script type="text/javascript">
var url="{{ route('like') }}";
var token="{{ Session::token() }}";
</script>
Here is the blade page :
#php
$like_count=0;
$dislike_count=0;
$like_statut="grey";
$dislike_statut="grey";
#endphp
#foreach ($services->likes as $like)
#php
if ($like->like ==1){
$like_count++;
}
else {
$dislike_count++;
}
if($like->like == 1 && $like->user_id==Auth::user()->id){
$like_statut="green";
}
else{
$dislike_statut="red";
}
#endphp
#endforeach
<div class="row">
<div class="col s12">
<button type="button"
data-like="{{$like_statut}}"
data-serviceid="{{$services->id}}"
class="like waves-effect waves-light btn {{$like_statut}}">
<i class="material-icons left">thumb_up</i>({{$like_count}})
</button>
</div>
</div>
<br>
<div class="row">
<div class="col s12">
<button type="button"
data-dislike="{{$dislike_statut}}"
class="dislike waves-effect waves-light btn {{$dislike_statut}}">
<i class="material-icons left">thumb_down</i>({{ $dislike_count}})
</button>
</div>
</div>
</div>
</div>
The route:
Route::post('/like','ServiceController#like')->name('like');
The "like" method in the controller:
public function like(Request $request)
{
$like_s = $request->like_s;
$service_id = $request->service_id;
$like = Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id, ]);
if (!$like) {
$new_like = new Like;
$new_like->service_id = $service_id;
$new_like->user_id = Auth::user()->id;
$new_like->like = 1;
$new_like->save();
} elseif ($like->like == 1) {
Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id,])
->delete()
;
} elseif ($like->like == 0) {
Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id,])
->update(array('like' => 1))
;
}
}
This row:
$like = Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id, ]);
seems incomplete, as it returns a query builder and not an object. The query builder has not a "like" property. If you want an object you should do: A first() at the end (or a get() followed by a foreach) seems to be missing.
I want to terminate a employee from the system. When clicks on terminate button it will popup a moadal asking whether wants to terminate or cancel. If terminate database value resign should be updated as 0, but right now button does not working.
Here is my code
controller
public function ajax_list()
{
$list = $this->employees->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $emp) {
$no++;
$row = array();
$row[] = $emp->employee_id;
$row[] = $emp->name;
$jid = $emp->job_title;
$desigdata = $this->employees->GetJobTitlebyID($jid);
$row[] = $desigdata->desc;
$did = $emp->department;
$deptdata = $this->employees->GetDepartmentbyID($did);
$row[] = $deptdata->title;
$secid = $emp->section;
$secdata = $this->employees->GetSectionbyID($secid);
$row[] = $secdata->desc;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void()" onclick="terminate_emp('."'".$emp->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Terminate</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->employees->count_all(),
"recordsFiltered" => $this->employees->count_filtered(),
"data" => $data,
);
echo json_encode($output);
}
public function ajax_terminate()
{
$this->_validate();
$data = array(
'resign' => $this->input->post('resign'),
);
$this->employees->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE, "id" => $this->input->post('id')));
}
Model
function terminate_emp($data)
{
$this->db->where('resign', 0);
$this->db->update('employees', $data);
}
View
function terminate_emp(id)
{
save_method = 'update';
$('#form')[0].reset();
$('.form-group').removeClass('has-error');
$('.help-block').empty();
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('employees_con/ajax_terminate/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
if(data.resign == 1)
{
//$('[name="resign"]').val(data.resign);
$('#resign').prop('checked', true);
}
$('[name="resign"]').val(data.resign);
$('#modal_formterminate').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Terminate Employee'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
<div class="modal fade" id="modal_formterminate" role="dialog">
<div class="modal-dialog modal-full" style="max-width: 600px">
<div class="modal-content">
<div class="modal-header bg-blue-steel bg-font-blue-steel">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title bold uppercase">Person</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div id="empWizard">
<p style="color: #0000cc"><b>Are You sure to Terminate this employee</b></p>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSaveterminate" onclick="save()" class="btn btn-primary">Terminate</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
In controller
$this->employees->update(array('id' => $this->input->post('id')), $data);
You are passing two parameters to update function of your model, one is an array and the other one $data that is also an array.
But In Model,
function terminate_emp($data)
{
$this->db->where('resign', 0);
$this->db->update('employees', $data);
}
you are just accepting one parameter in the update function.
First of all you are making GET request through AJAX and on Controller function ajax_terminate() you are accessing variables using POST. You resign value is not passing through ajax and you are trying to get on controller function ajax_terminate(). See below code:-
function terminate_emp(id)
{
save_method = 'update';
$('#form')[0].reset();
$('.form-group').removeClass('has-error');
$('.help-block').empty();
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('employees_con/ajax_terminate/')?>/",
type: "POST",
dataType: "JSON",
data: {id:id,resign:YOUR_RESIGN_VALUE}
success: function(data)
{
$('[name="id"]').val(data.id);
if(data.resign == 1)
{
//$('[name="resign"]').val(data.resign);
$('#resign').prop('checked', true);
}
$('[name="resign"]').val(data.resign);
$('#modal_formterminate').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Terminate Employee'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
Change Model to
function terminate_emp($where,$data)
{
$this->db->where($where);
$this->db->update('employees', $data);
}