How to solve datatable 403 forbidden in production Laravel? - php

I have some code to request datatable via jquery ajax that returns:
403 forbidden
in a production environment, it's working properly in my local environment.
When I open url directly in browser it shows JSON array.
this is my ajax request:
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var state = true;
var otable = $('#example').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('get.data') }}",
columns: [
{ data: 'CountryCode', name: 'CountryCode' },
{ data: 'CountryName', name: 'CountryName' },
{ data: 'FgActive', name: 'FgActive' },
{ data: 'action', name: 'action' }
]
});
my route
Route::get('get-data-my-datatables', [
'as'=>'get.data',
'uses'=>'CountryController#getData'
]);
Below is function in controller
public function getData()
{
$country = Country::all();
return datatables()
->of($country)
->addColumn('action', function ($country) {
return
'<button type="button" name="'.$country->CountryCode.'" class="btn btn-primary btn-sm fa fa-pencil" id="btnEdit" data-toggle="modal"></button>
<button type="button" name="'.$country->CountryCode.'" class="btn btn-danger btn-sm fa fa-trash" id="btnDel" data-toggle="modal"></button>'
;
})
->make(true);
}
Thank you for your attention.
Update
As requested, this is my network tab:

Related

The GET method is not supported for this route Laravel + ConfirmBox

I tried to solve this problem:
The GET method is not supported for this route. Supported methods:
POST.
But I can not find right way and error on Laravel 8.
Here is blade:
<a href="{{ route('operDel',$data->id) }}" class="btn btn-danger btn-sm"
data-tr="tr_{{$data->id}}"
data-id="{{$data->id}}"
data-toggle="confirmation"
data-btn-ok-label="Delete" data-btn-ok-icon="fa fa-remove"
data-btn-ok-class="btn btn-sm btn-danger"
data-btn-cancel-label="Cancel"
data-btn-cancel-icon="fa fa-chevron-circle-left"
data-btn-cancel-class="btn btn-sm btn-default"
data-title="Are you sure you want to delete ?"
data-placement="left" data-singleton="true">Delete</a>
And JavaScript in this blade
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success']) {
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
Here is Route
Route::delete('operDel/{id}', '\App\Http\Controllers\OperationController#destroy')->name('operDel')->middleware('auth');
And this is Controller
public function destroy($id)
{
Kvit::where('id', $$id)->delete();
return response()->json([
'success'=>"Product Deleted successfully.", 'tr'=>'tr_'.$id
]);
}
What I missed?
You need to pass method to the server.
$.ajax({
url: "operDel/"+id,
type: 'get',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function(data){
//do stuff
},
error: function(data){
//do stuff
}
);
Solved by this code
Blade
<button class="btn btn-icon btn-flat-danger deleteRecord"
data-id="{{$data->id}}">
<i class="fas fa-trash"></i>
</button>
JavaScript
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
if(confirm('Do you want to delete?')){
$.ajax(
{
url: "operDel/"+id,
type: 'post',
cache: false,
data: {
"id": id,
"method": 'post',
"_token": token,
},
dataType: "json",
success: function(response) {
if(response.status == "success"){
window.location.href='/operations';
}else if(response.status == "error"){
{toastr['error'](
'Please check datas..',
'You can not delete this!',
{
closeButton: true, tapToDismiss: true, progressBar: true,
}
);
}
}
},
});
}
});

Laravel - Ajax project ( getClientOriginalName on null)

So I have Laravel project and I use Ajax for CRUD.
This is my Controller:
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$rules = array(
'naziv' => 'required|max:90|unique:restaurants',
'adresa' => 'required|max:150',
'min_dostava' => 'required|max:5',
'vrijeme_dostave' => 'required|max:10',
'cijena_dostave' => 'required|max:5',
'podrucije_grada' => 'required',
'br_telefona' => 'required|numeric|unique:restaurants',
'kuhinja_id' => 'required',
'user_id' => 'required',
'lokacija' => 'max:999',
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json(['errors' => $error->errors()->all()]);
}
// logo
$logo = $request->file('logo');
$filename = $logo->getClientOriginalName();
//Fullsize
$logo->move(public_path().'/uploads/',$filename);
$image_resize = Image::make(public_path().'/uploads/'.$filename);
$image_resize->fit(800, 600);
$image_resize->save(public_path('uploads/'.$filename));
// logo finish
$restaurant = Restaurant::updateOrCreate(['id' => $request->restaurant_id],
[
'naziv' => $request->naziv,
'adresa' => $request->adresa,
'min_dostava' => $request->min_dostava,
'vrijeme_dostave' => $request->vrijeme_dostave,
'cijena_dostave' => $request->cijena_dostave,
'podrucije_grada' => $request->podrucije_grada,
'br_telefona' => $request->br_telefona,
'kuhinja_id' => $request->kuhinja_id,
'user_id' => $request->user_id,
'lokacija' => $request->lokacija,
'logo' => $filename
]);
$restaurant->save();
if($restaurant->wasChanged()){
return response()->json(['success'=>'Uspjesno ste izmijenili restoran.']);
}
return response()->json(['success'=>'Uspjesno ste dodali novi restoran.']);
}
And a part of form where is file input in my blade:
<div class="form-group">
<label for="exampleFormControlFile1" class="form-control-sm">Logorestorana</label>
<input type="file" class="form-control-file" id="logo" name="logo" value="">
</div>
And my jquery script:
<script type="text/javascript">
$(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('#dataTable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('admin.restaurants.index') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'logo', name: 'logo'},
{data: 'naziv', name: 'naziv'},
{data: 'adresa', name: 'adresa'},
{data: 'min_dostava', name: 'min_dostava'},
{data: 'vrijeme_dostave', name: 'vrijeme_dostave'},
{data: 'cijena_dostave', name: 'cijena_dostave'},
{data: 'podrucije_grada', name: 'podrucije_grada'},
{data: 'br_telefona', name: 'br_telefona'},
{data: 'kuhinja_id', name: 'kuhinja_id'},
{data: 'user_id', name: 'user_id'},
{data: 'lokacija', name: 'lokacija'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$('#createNewProduct').click(function () {
$('#saveBtn').val("create-product");
$('#restaurant_id').val('');
$('#productForm').trigger("reset");
$('#modelHeading').html("Create New Product");
$('#ajaxModel').modal('show');
});
$('body').on('click', '.editProduct', function () {
var restaurant_id = $(this).data('id');
$.get("{{ route('admin.restaurants.index') }}" +'/' + restaurant_id +'/edit', function (data) {
$('#modelHeading').html("Edit Product");
$('#saveBtn').val("edit-user");
$('#ajaxModel').modal('show');
$('#restaurant_id').val(data.id);
$('#naziv').val(data.naziv);
$('#adresa').val(data.adresa);
$('#min_dostava').val(data.min_dostava);
$('#vrijeme_dostave').val(data.vrijeme_dostave);
$('#cijena_dostave').val(data.cijena_dostave);
$('#podrucije_grada').val(data.podrucije_grada);
$('#br_telefona').val(data.br_telefona);
$('#kuhinja_id').val(data.kuhinja_id);
$('#br_telefona').val(data.br_telefona);
$('#lokacija').val(data.lokacija);
$('#logo').val(data.logo);
})
});
$('#saveBtn').click(function (e) {
e.preventDefault();
$(this).html('+ Novi restoran');
$.ajax({
data: $('#productForm').serialize(),
url: "{{ route('admin.restaurants.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
var html = '';
if(data.errors)
{
html = '<div class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
html = '<div class="alert alert-success alert-dismissible fade show" role="alert"><strong><i class="fas fa-check-circle"></i> ' + data.success + '</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button></div>';
$('#productForm').trigger("reset");
$('#ajaxModel').modal('hide');
table.draw();
}
$('#form_result').html(html);
}
});
});
$('body').on('click', '.deleteProduct', function () {
var restaurant_id = $(this).data("id");
confirm("Are You sure want to delete !");
$.ajax({
type: "DELETE",
url: "{{ route('admin.restaurants.store') }}"+'/'+restaurant_id,
success: function (data) {
table.draw();
html = '<div class="alert alert-danger alert-dismissible fade show" role="alert"><strong><i class="fas fa-trash"></i> ' + data.success + '</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button></div>';
$('#form_result').html(html);
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
ISSUE
I'm keep getting same issue in my Network console and it is
Call to a member function getClientOriginalName() on null
What I'm doing wrong here?
I also included #crsf in form and enctype="multipart/form-data".
And I'm also using Laravel Intervention Image.
Please help.
You can not pass enctype and mimetype in ajax function. Please try this
$.ajax({
data: $('#productForm').serialize(),
url: "{{ route('admin.restaurants.store') }}",
type: "POST",
dataType: 'json',
enctype: 'multipart/form-data',
mimeType: 'multipart/form-data',
success: function (data) {
var html = '';
if(data.errors)
{
html = '<div class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
html = '<div class="alert alert-success alert-dismissible fade show" role="alert"><strong><i class="fas fa-check-circle"></i> ' + data.success + '</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button></div>';
$('#productForm').trigger("reset");
$('#ajaxModel').modal('hide');
table.draw();
}
$('#form_result').html(html);
}
});
The error message means that 'logo' is not in the request.
When you try to get it with
$logo = $request->file('logo');
it is probably null. When you then try to get the filename
$filename = $logo->getClientOriginalName();
it fails because $logo=null.
Try to use
dd($request->input());
to see what is actually in the request. Or you can log it with
Log::info("Request data = ", ['request' => $request->input()])

Server Side dataTable dropdown filter only showing data in first page | PHP, SQL SERVER

This is a working script, but the dropdown option only displays the first 10 data and not all data in the table. What seems to be the problem here?
$(function() {
$('#example').DataTable( {
dom: "Bfrtip",
ajax: {
url: "account_type_table.php",
type: "POST"
},
serverSide: true,
columns: [
{ data: "seriesno" },
{ data: "accounttype" },
{ "data": "seriesno", "name": " ", "autoWidth": true, "render": function (data, type, full, meta) {
return "<button class='btn btn-success btn-sm btn-flat edit' data-id='"+full.seriesno+"'><i class='fa fa-edit'></i> Edit</button> <button class='btn btn-danger btn-sm btn-flat delete' data-id='"+full.seriesno+"'><i class='fa fa-trash'></i> Delete</button>";}
}
],
initComplete: function () {
this.api().columns([0,1]).every( function () {
var column = this;
var select = $('<select class="form-control"><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $(this).val();
column.search( this.value ).draw();
} );
console.log(column.data().unique());
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
},
select: false,
buttons: [],
} );
} );

Laravel Route call via AJAX gets wrong URL 404 (Not Found)

I have the following route defined in my web.php
Route::delete('/contributions/contribution/destroy', 'ContributionController#destroy');
In my blade file I have a button that when clicked displays a sweetalert to confirm deletion. This works correctly, but when the user presses the delete button instead of it going to the URL defined in Ajax it goes to an incorrect URL and logs the following error:
jquery.min.js:4 DELETE http://localhost/contributions/batches/batch/edit 404 (Not Found)
Here is button code
<td class="text-center"><button type="button" class="btn btn-danger btn-sm btn-icon btn-destroy"
data-batch-id="{{ $batch->id }}"
data-id="{{ $contribution->id }}"
data-amount="${{ number_format ($contribution->contribution_amount, 2, '.', ',') }}"
data-contributor="{{ $contribution->first_name.' '.$contribution->last_name }}"
><i class="fa fa-times"></i></button>
</td>
Here is my script
<script>
$(document).on('click', '.btn-destroy', function (e) {
e.preventDefault();
var batchId = $(this).data('batch-id');
var id = $(this).data('id');
var amount = $(this).data('amount');
var contributor = $(this).data('contributor');
swal({
title: "Delete?",
text: "Do you want to delete contribution for "+ amount +" from "+ contributor +"?",
type: "error",
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: "Delete",
closeOnConfirm: false
},
function() {
$.ajax({
url: "{{ url('/contributions/contribution/destroy') }}",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: "DELETE",
data: {batch:batchId, contribution:id},
success: function (data) {
console.log(data);
}
});
});
});
oddly enough, refreshing the page after the error returns my session flash message from my controller's destroy function
*Note: I did add the DELETE verb to IIS, before this I was receiving:
405 (METHOD NOT ALLOWED)
Any ideas?
After two days of reading and wrenching I have a working solution:
route:
Route::delete('/contributions/contribution/destroy', 'ContributionController#destroy');
link html:
<a href="#" class="btn btn-danger btn-sm btn-icon btn-destroy"
data-id="{{ $contribution->id }}"
data-amount="${{ number_format ($contribution->contribution_amount, 2, '.', ',') }}"
data-contributor="{{ $contribution->first_name.' '.$contribution->last_name }}"><i class="fa fa-times"></i></a>
jquery/ajax:
<script>
$(document).on('click', '.btn-destroy', function (e) {
e.preventDefault();
var contributionId = $(this).data('id');
var amount = $(this).data('amount');
var contributor = $(this).data('contributor');
swal({
title: "Delete?",
text: "Do you want to delete contribution for "+ amount +" from "+ contributor +"?",
type: "error",
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: "Delete",
closeOnConfirm: false
},
function() {
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
method: "DELETE",
url: "{{ url('/contributions/contribution/destroy') }}",
data: {contributionId:contributionId},
success: function (msg) {
if ( msg.status === 'success' ) {
swal("Deleted", msg.msg, "success");
setInterval(function() {
window.location.reload();
}, 3900);
}
},
error: function(msg) {
swal("Error!", "Something went wrong.", "error");
console.log(msg.status);
}
});
});
});
</script>
controller:
public function destroy(Request $request)
{
if ( $request->ajax() ) {
Contribution::find($request->contributionId)->delete();
return response(['msg' => 'Entry deleted', 'status' => 'success']);
}
return response(['msg' => 'Failed deleting the entry', 'status' => 'failed']);
}
Works perfectly!
Try this style of ajax
$.ajax({
url: "{{ url('/contributions/contribution/destroy') }}",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
'data':{
'_method':'delete',
'_token':'{{ csrf_token() }}',
},
'method':'post'
});
in my case I removed the error by running simple classic:
php artisan route:clear
or you can launch that remotely. Create a route and a Controller and call it via browser link:
Route::get('/b/{x}', 'for_stuff\BController#kukuku');
and put into the controller's function:
Artisan::call('route:clear');
say:
https://mysite/b/r

Ajax keeps refreshing the entire page instead of just the comment section

I'm working on a project with codeigniter and I decided to implement ajax into the comment section so that the whole page is not refreshed when the user submits his comment. The comment is displayed automatically but the page keeps getting refreshed. I don't know what I am doing wrong here but any help would be appreciated.
MODEL:
public function create_comments($post_id){
$data = array(
'post_id' => $post_id,
'body' => $this->input->post('body'),
'users_id' => $this->session->userdata('user_id')
);
return $this->db->insert('comments',$data);
}
CONTROLLER:
public function create($post_id){
//checking if user is logged in
if(!$this->session->userdata('isLoggedIn')){
redirect('users/login');
}
$slug = $this->input->post('slug');
$data['post'] = $this->post_model->get_posts($slug);
$this->form_validation-> set_rules('body', 'Comment', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('posts/view', $data);
$this->load->view('templates/footer');
$this->session->set_flashdata('comment_error', 'comment field is empty comment');
redirect('posts/'.$slug,'refresh');
} else {
$this->comments_model->create_comments($post_id);
redirect('posts/'.$slug);
}
}
VIEW:
<?php echo form_open_multipart('comments/create/'.$post['id'], 'id="comnt"'); ?>
<div class="panel-footer">
<!--//THIS IS THE FIELD WHICH COMMENTS WOULD BE ADDED-->
<div class="">
<input type="hidden" name="slug" value="<?php echo $post['slug']; ?>">
<small class="text-center text-danger"><?php echo form_error('body'); ?></small>
<div class="input-field">
<textarea id="icon_prefix2" name="body" class="materialize-textarea" rows="3"></textarea>
<label for="icon_prefix2">Comments</label>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action" id="submit">comment <i class="material-icons right">send</i></button>
</div>
</div>
</form>
AJAX:
$('#submit').click(function() {
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>comments/create",
type: "POST",
data: form_data,
success: function(msg) {
alert("msg");
}
});
return true;
});
Use jquery preventDefault() function to prevent your form to be submitted
$('#submit').click(function(e) {
e.preventDefault();
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>"+"comments/create",
type: "POST",
data: form_data,
success: function(msg) {
alert("msg");
}
});
return true;
});
Try the done property to set the success handler. Also, as this is an event over a DOM element, you should attach it when the DOM is ready:
$(document).ready(function() {
$('#submit').click(function(event) {
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>comments/create",
type: "POST",
data: form_data,
}).done(function(msg) {
alert(msg);
}).fail(jqXHR, textStatus) {
alert('ERROR: ' + textStatus);
});
// return is not necessary here
// return true;
});
$("#comnt").submit(function(e) { // Prevent the form submitting
e.preventDefault();
});
});
As this already attaches an event, you should remove the onclick="comment()" property from your button:
<button class="btn waves-effect waves-light" type="submit" id="submit">comment
<i class="material-icons right">send</i>
</button>
Try this hope it work
$('#submit').click(function(event) {
e.preventDefault(); //stop actual action of browser
var form_data = {
body: $("#icon_prefix2").val()
};
$.ajax({
url: "<?php echo base_url();?>comments/create",
type: "POST",
data: form_data,
success: function(msg) {
alert("msg");
}
});
return true;
});
Change button type button instead of submit
<button class="btn waves-effect waves-light" type="button" name="action" id="submit">comment
<i class="material-icons right">send</i>
</button>

Categories