I am using DataTables 1.10.16 and using Ajax I am trying to build the table.
The table works fine in my backend but in frontend I am getting 302 redirect.
But if I call the Ajax URL in the browser it returns the data correctly.
I am not getting where I am going wrong
This is how initialize DataTable
var datatable = $('#reports-info-table');
datatable.DataTable({
"processing": true,
"serverSide": true,
"ajax": BASE_URL + '/user/reported-business-info',
"columns": [{
data: 'slno',
name: 'slno'
},
{
data: 'report',
name: 'report'
},
{
data: 'business_name',
name: 'business_name'
},
{
data: 'show',
name: 'show',
orderable: false,
searchable: false
}
]
});
This is how return the DataTable
return Datatables::of($reports)
->editColumn('report', function ($reports) {
return $reports->vchr_report_message;
})
->editColumn('business_name', function ($reports) {
return $reports->business->vchr_business_name;
})
->addColumn('show', function ($reports) {
if ($reports->int_status == 1) {
return '
<div class="btn-group btn-collection btn-icon-group">
<a class="btn btn-info" data-toggle="tooltip" title="View"> <i class="ua-icon-control-export btn-icon"></i></a>
</div>';
} //If Status is not in active state
else {
return '
<div class="btn-group btn-collection btn-icon-group">
<a class="btn btn-info" data-toggle="tooltip" title="View"> <i class="ua-icon-control-export btn-icon"></i></a>
</div>';
}
})
->rawColumns(['show'])->toJson(true);
I found out that my middleware was stopping the Ajax call and hence getting redirected.
Original Code
if (!$request->ajax() && Auth::check() && (Auth::user()->int_role_id == Roles::ROLE_USER)) {
return $next($request);
}else if (!$request->ajax() && !Auth::check() ){
$url = Request()->path();
Session::put('loginRedirect', $url);
return redirect('/login');
}
Changed TO
if (Auth::check() && (Auth::user()->int_role_id == Roles::ROLE_USER)) {
return $next($request);
}else if (!$request->ajax() && !Auth::check() ){
$url = Request()->path();
Session::put('loginRedirect', $url);
return redirect('/login');
}
Now it Works.
Related
when I want to delete data, the data in the rekap table is deleted but the file_rekap table and image_rekap table and those in the folder also don't want to be deleted
Controller Rekap
public function delete_rekap($id){
$data = rekap::findOrfail($id);
$images=image_rekap::where("rekap_id",$data->id)->get();
foreach($images as $image){
if (File::exists("images_rekap/".$image->image)) {
File::delete("images_rekap/".$image->image);
}
}
$files= file_rekap::where("rekap_id",$data->id)->get();
foreach($files as $file){
if (File::exists("rekap_file/".$file->file)) {
File::delete("rekap_file/".$file->file);
}
}
$data->delete();
return redirect()->route('rekap')->with('success','Data berhasil dihapus');
}
this my button
<a href="#" class="btn btn-danger delete m-1" data-id="{{ $row->id}}" data-customer="{{ $row->customer}}" >DELETE</a>
script
$('.delete').click(function(){
var rekapid = $(this).attr('data-id');
var customer = $(this).attr('data-customer');
swal({
title: "Yakin",
text: "Kamu akan menghapus data dengan nama "+customer+" ",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
window.location = "/delete_rekap/"+rekapid+" "
swal("Data Berhasil Terhapus", {
icon: "success",
});
} else {
swal("Data tidak jadi dihapus");
}
});
});
</script>
what steps should i do to fix it
if you want to delete, try
unlink php
BLADE FILE
<td><button class="deleteuser" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >DELETE</button>
</td>
AJAX
$(document).ready( function () {
$(".deleteuser").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
});
CONTROLLER
public function destroyuser($id){
$this->authorize('Admin');
User::find($id)->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
return view('viewuser');
}
If I click on delete button, there is no response. Any suggestion or correction will be appreciated. Thanks in advance
I don't know if the JS is in a different file but to check if the "$( document ).ready()" is working add a console.log() call at the beginning.
$(document).ready( function () {console.log("document is ready")
$(".deleteuser").click(function(){
Refresh the page and check if "document is ready" is logged to the console.
If it isn't then the javascript is not loading
Check if the route is properly defined
You can replace your url as this and check:
var id = data.id;
var url = "{{route('your_route',":id") }}";
url = url.replace(':id', id);
pass url in your ajax url param
Or make above changes:
BLADE FILE
<td>
<button style="background-color: red;" onclick="clickOffConfirmed" title="Delete" class="btn btn-sm btn-clean btn-icon btn-icon-md delete"><i class="la la-trash" style="color: white;"></i></button>
</td>
SCRIPT
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function ()
{
var obj = $(this);
var id=$(this).closest('td').find(".delete_id").val();
var result = confirm("Are you sure want to delete?");
if(result)
{
$.ajax(
{
type: "POST",
url: "{{route('delete_method')}}",
data: {
'_token': $('input[name="_token"]').val(),
'id': id
},
cache: false,
success: function (data)
{
if (data.status === 'success')
{
window.location = "{{route('redirect_route')}}";
toastr["success"]("Deleted Successfully", "Success");
}
else if (data.status === 'error')
{
location.reload();
toastr["error"]("Something went wrong", "Opps");
}
}
});
}
});
});
</script>
Controller
public function delete_method(Request $request)
{
$del = ModelName::findOrFail($request->id)->delete();
if($del)
{
return response()->json(['status' => 'success']);
}
else{
return response()->json(['status' => 'error']);
}
}
Route
Route::post('/test/delete','TestController#delete_method')->name('delete_method');
In your ajax codes, change this:
url: "user/delete/"+id,
To:
url: "{{ url('user/delete') }}/" + id
If your ajax codes are inside of your blade file also you can use this way:
url: "{{ route('YOUR_ROUTE_NAME', $user->id) }}/"
You incorrectly define delete function!
change
User::find($id)->delete($id);
To
User::find($id)->delete();
I want to retrieve data from DB to my user Dashboard. User Identify using Contact No.
I run AJAX query to retrieve all adds. its running well.
but I need to retrieve data under his user ID (ContactNo). here I add AJAX code.
user data avaiable in AUTH -> {{ Auth::user()->ContactNo }}
$(document).ready(function($){
//alert("jquery running");
getAll();
});
//getting all rows from the database
function getAll() {
$.ajax({
url: '{{ route('Myadds', app()->getLocale()) }}',
type: 'GET',
})
.done(function(data) {
alert("run")
$.each(data, function(index, val) {
$('#data').append('<tr>')
$('#data').append('<td>'+val.id+'</td>')
$('#data').append('<td>'+val.Sdescription+'</td>')
$('#data').append('<td>'+val.created_at+'</td>')
$('#data').append('<td><button class="btn btn-xs btn-danger" data-id="'+val.id+'">Delete</button><button class="btn btn-xs btn-info" data-id="'+val.id+'">Edit</button></td>')
$('#data').append('</tr>')
});
})
.fail(function() {
alert("fail")
console.log("error");
})
}
</script>
You need to pass de contactNo parameter in your query:
function getAll() {
$.ajax({
url: '{{ route('Myadds', app()->getLocale()) }}',
type: 'GET',
data: {
contact_no: contactNo,
},
})
.done(function(data) {
alert("run")
$.each(data, function(index, val) {
$('#data').append('<tr>')
$('#data').append('<td>'+val.id+'</td>')
$('#data').append('<td>'+val.Sdescription+'</td>')
$('#data').append('<td>'+val.created_at+'</td>')
$('#data').append('<td><button class="btn btn-xs btn-danger" data-id="'+val.id+'">Delete</button><button class="btn btn-xs btn-info" data-id="'+val.id+'">Edit</button></td>')
$('#data').append('</tr>')
});
})
.fail(function() {
alert("fail")
console.log("error");
})
}
So in your controller now you can filter:
public function getData(Request $request){
$contact_no = $request->contact_no;
$query = DB::table('my_table');
if($contact_no){
$query->where('contact_no',$contact_no)
}
return response()->json($query->get());
}
Or directly use the session of the user:
public function getData(Request $request){
$contact_no = Auth::user()->ContactNo;
$query = DB::table('my_table');
$query->where('contact_no',$contact_no)
return response()->json($query->get());
}
public function Myadds(){
try{
return add::where('userID', Auth::user()->ContactNo)->get();
}catch(Exception $e){
return 'false';
}
}
I have the next table..
The IDOP column is a key that I'm using for connect in my app instead of email... I would like to be able for filter the IDOP of each user... So the user should only be able to see the rows with
of its corresponding IDOP, how could I filter only his IDOP?
this is the function of my datatable
$('#user_contactabilidadasesor').DataTable({
processing: true,
"scrollX": true,
//serverSide: true,
ajax: {
url: "{{ route('contactabilidadasesor.index') }}",
},
columns: [
{
data: 'idop',
name: 'l.idop',
className: 'uniqueClassName'
},
{
data: 'idop_asesor',
name: 'idop_asesor',
searchable: false, render: function ( data, type, row ) {
if (data == null){ return ''; }else{return (row['idop_asesor'] + ' ' + row['ape_asesor'])};
},
className: 'uniqueClassName'
}
],
});
And this is my query
public function index(Request $request)
{
if($request->ajax())
{
$data = DB::table('tbl_lista_contactabilidad as a')
->select('a.id','a.postventaatcs_id')
->leftjoin('tbl_equipo_postventaatcs as h','h.id','=','a.postventaatc_id')
->leftjoin('users as l','l.id','=','h.asesor_id')
->select(array('a.id','l.name as idop_asesor','l.apellido as ape_asesor','l.idop'));
return DataTables::of($data)
->addColumn('action', function($data){
$button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Auditar</button>';
//$button .= ' <button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
return $button;
})
->rawColumns(['action'])
->make(true);
}
return view('contactabilidadasesor');
}
For filtering you have to use ->where('IDOP', auth()->user()->IDOP) (for single user) of ->whereIn('IDOP', [array of filtering idops]) for multiple IDOPs
Hi all i am trying to delete my record from datatable with out page refresh in codeigniter i have used ajax i don't know where i have done mistake its not deleting the record
Below is the my view:
<tbody>
<?php
if (!empty($employees)) {
foreach ($employees as $emp) {
?>
<tr>
<td><?php echo $emp->emp_name; ?></td>
<td><?php echo $emp->salary; ?></td>
<td class='text-center'>
<button type="submit" class="btn btn-info btn-xs confirmation" name="login"><i class='fas fa-edit'></i></button>
</td>
<td class='text-center'>
<button type="submit" onClick="return ConfirmDelete()" class="btn btn-danger btn-xs confirmation empdelete" id="<?php echo $emp->id;?>"><i class='fas fa-times'></i></button>
</td>
</tr>
<?php
}
}
?>
</tbody>
<script>
$(document).ready(function(){
$(".empdelete").click(function(e){
alert();
e.preventDefault();
$.ajax({
alert();
type: "POST",
url: "<?=site_url('Employee/delete');?>",
cache: false,
data: {id:$(this).attr("id")}, // since, you need to delete post of particular id
success: function(data) {
if (data){
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
});
});
</script>
Here is the my controller:
function delete()
{
$id = $this->input->post('id'); // get the post data
$empdelete=$this->Emp_model->delete($id);
if($empdelete){
echo true;
} else {
echo false;
}
}
Here is my model's method delete:
function delete($id)
{
$sql = "DELETE FROM employees WHERE id=?";
return $this->db->query($sql,array($id));
}
Can any one help me how can i do that with out page refresh i want to delete my record.
Thanks in advance.
Try this:
$(document).ready(function () {
function ConfirmDelete() {
var x = confirm("Are you sure you want to delete?");
if (x)
return true;
else
return false;
}
$(".empdelete").click(function (e) {
var obj = $(this);
e.preventDefault();
//alert(); what's this do?
if (ConfirmDelete() == false) {
return false;
}
$.ajax({
//alert(); this can't go here
type: "POST",
url: "<?php echo site_url('Employee/delete'); ?>",
cache: false,
data: {id: $(this).attr("id")},
success: function (data) {
console.log('ajax returned: ');
console.log(data);
if (data) {
obj.closest('tr').remove();
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
});
});
and remove HTML onClick:
<button type="submit" class="btn btn-danger btn-xs confirmation empdelete" id="<?php echo $emp->id;?>"><i class='fas fa-times'></i></button>
Hope this will help you :
Your button should be like this :
<button type="button" onClick="return ConfirmDelete(this)" class="btn btn-danger btn-xs confirmation empdelete" data-id="<?=$emp->id;?>"><i class='fas fa-times'></i></button>
Your ajax code should be like this :
function ConfirmDelete(obj)
{
var x = confirm("Are you sure you want to delete?");
if (x == true)
{
var id = $(obj).data('id');
alert(id);
if (id != '')
{
//do you ajax here
$.ajax({
type: "POST",
url: "<php echo site_url('Employee/delete'); ?>",
cache: false,
data: {'id': id},
success: function (data) {
console.log('ajax returned: ');
console.log(data);
if (data) {
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
}
}
else
{
return false;
}
}
Your controller should be like this :
function delete()
{
$id = $this->input->post('id'); // get the post data
$empdelete = $this->Emp_model->delete($id);
if($empdelete)
{
echo true;
} else
{
echo false;
}
exit;
}
Your delete method should be like this :
function delete($id)
{
$this->db->where('id',$id);
$this->db->delete('employees');
return $this->db->affected_rows();
}