Is there other way to set url using route? - ajax

i'm just starting to learn ajax laravel im just following a tutorial then it not working for me. thanks
my ajax looks like this:
$(document).ready(function(){
$('#courseTable').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{{ route('courses.index') }}}",
},
then in routes:
Route::resource('courses', 'CourseController');
then for my coursecontroller:
public function index()
{
// $courses = Course::orderBy('description','asc')->paginate(8);
if (request()->ajax()) {
return datatables()->of(Course::latest()->get())
->addColumn('action', function($data){
$button = '<button type="button" name="edit" id="'.$data->courseID.'"
class="edit btn btn-warning btn-sm">Edit</button>';
$button .= ' ';
$button .= '<button type="button" name="delete" id="'.$data->courseID.'"
class="delete btn btn-warning btn-sm">Delete</button>';
return $button;
})
->rawColumns(['action'])
->make(true);
}
return view('registrar.courses.index');
// ->with('courses', $courses)
}
this error shows up like this:
app.js:16034 GET http://odrs.test/%7B%7B%7B%20route('courses.index')%20%7D%7D%7D?draw=1&colum 404 (Not Found)

it's impossible to write a blade template in a separate javascript file.
you have probably 2 ways to do it:
join your eventListener in your blade view as a child.
transfer your JS file to your views file, change its extension to blade.php and include it in the view between script tags:
<script>
#include("my-view-js")
</script>

Related

How to add button to open url with parameter in datatables Laravel 8

I have some data shown in my datatable view, I want to add button to each data to open detail page which can show more detail information
public function Task(Request $request)
{
if ($request->ajax()) {
$data = DB::table('posts')
->where('jabatan', Auth::user()->jabatan)
->select('user_id', 'name', DB::raw('count(user_id) as total'))
->selectRaw('SUM(status = "Selesai") as selesai')
->selectRaw('count(user_id) - SUM(status = "Selesai") as belum')
->groupBy('name')
->groupBy('user_id')->get();
return Datatables::of($data)
->addColumn('action', function ($row) {
$btn = ' <span class="fas fa-eye"></span>';
return $btn;
})
->rawColumns(['action'])
->addIndexColumn()
->make(true);
}
return view('task.Task');
}
the button can appear in my datatable, but it will open %7B%7Broute('detail.index',$row->user_id)%7D%7D ,
If in a html table I can use <a class="btn btn-info btn-sm" href="{{ route('detail.index',$post->id) }}">Show</a>
how to make the button to open /detail in url? thanks in advance
as your in already in php so don't use {{ }} blade syntax use
$btn = '<span class="fas fa-eye"></span>';

how to custom filter search in datatable laravel,

ajax
$(document).ready(function(){
tabel_sales = $('#tabel_sales').DataTable({
'bLengthChange': false,
scrollXInner: true,
dom : 'frtp',
processing : true,
serverside : true,
ajax : {
'url' : '{{ url("data/data_sales") }}',
'data' : function(data){
month = $('#month').val();
console.log(data);
data.searchByMonth = month;
}
}
})
$('#month').change(function(e){
tabel_sales.draw();
})
})
controller
$testing = $request->get('searchByMonth');
$get_po_apar = DB::table('tabel_header_po')
->where([
['kode_mitra', Auth::user()->kode_mitra],
['no_po', 'LIKE', '%TRX%'],
['created_by', $gd->kode_user]
])
->whereMonth('created_at',$testing)
->get();
if (count($get_po_apar) > 0) {
$po = '<button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-envelope"></i> ' . count($get_po_apar) . ' Po Apar</button>';
$fetch[] = $po;
} else {
$po = '<button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-envelope"></i> 0 Po Apar</button>';
$fetch[] = $po;
}
i have problem, I want to display data based on the month dropdown I chose, automatically the data that appears will change based on the dropdown
please Help me!
You can try using:
tabel_sales.columns("index column" or "column name").search("value").draw();
This link: https://datatables.net/reference/api/column().search()
May I help you!

set entity attribute (selecting a radio button) with ajax in Symfony 2.5

I want to integrate Ajax in my Symfony project (Symfony 2.5 and jQuery 3). I want to update an attribute of an Entity when I select a radio button. For now, I can get the id of the row that I select. I have searched how to implement this, but I have not succeeded.
JS code:
$(document).ready(function(){
$("input:radio[name=locacion_destacada]").click(function () {
var id = $(this).parent().parent().attr('dataId');
alert(id);
$.ajax({
url: "/update-destacado",
type: "POST",
data: { id : id },
success: function (response) {
alert(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error: ' + errorThrown);
}
});
});
});
Any help is greatly appreciated.
You can do that in the controller by calling it in the url of ajax :
url : {{ path('your_route', {'id': id})}};
and in the controller function you can update your entity as you like
You need a controller action, which is called by your "update-destacado" route. Then read the ID from the request and update your entity.
I could resolve it. I followed the idea of this page (answer n°8), also keep in mind your answers. Thanks for your help.
Controller code:
public function DestacadoAction(Request $request, $id){
$em = $this->getDoctrine()->getManager();
//Encontrar la locacion que ya estaba como destacada y dejarla como destacado=false
$locacionDestacadaAntigua = $em
->getRepository('FilmsBundle:Locaciones')
->findOneBy(
array(
'destacado' => true
));
$locacionDestacadaAntigua->setDestacado(false);
$em->persist($locacionDestacadaAntigua);
$em->flush();
$em = $this->getDoctrine()->getManager();
//Dejar como destacada la nueva locacion
$locacionDestacadaNueva = $this->getDoctrine()
->getRepository('FilmsBundle:Locaciones')
->findOneBy(
array(
'idLocacion' => $id
));
$locacionDestacadaNueva->setDestacado(true);
$em->persist($locacionDestacadaNueva);
$em->flush();
return new Response("Ha seleccionado la locación \"" . $locacionDestacadaNueva->getNombreLocacion() . "\" como destacada.");
}
JS Code:
$(document).ready(function(){
$(".button").on("click", function (e) {
$.post(this.href).done(function (response) {
alert(response);
location.reload();
});
});
});
Twig code:
{% if locacion.destacado == true %}
<td align="center">
<a class="button" href="{{ path('admin_destacado_update', { 'id': locacion.idLocacion }) }}">
<button class="btn btn-default">
<i class="glyphicon glyphicon-ok"></i>
</button>
</a>
</td>
{% else %}
<td align="center">
<a class="button" href="{{ path('admin_destacado_update', { 'id': locacion.idLocacion }) }}">
<button class="btn btn-sm">
<i class="glyphicon glyphicon-remove"></i>
</button>
</a>
</td>
{% endif %}

How to use variable data after Ajax Call Success - Laravel

I created a small file manager to manage my files. On the one hand, the folder structure is shown thanks to JsTree. On the right I would like that based on the click on the left folder I was shown the files contained in that folder.
At the click an Ajax call is made which calls the selectFiles method to go through the routes. Now in the console i see the correct data, but i don't know how to use it into foreach in the blade.
AJAX:
// chiamata Ajax per selezionare files in base all'id
$('#treeview').on("select_node.jstree", function (e, data) {
var id = data.node.id;
$.ajax({
type: 'POST',
url: 'archivio_documenti/+id+/selectFiles',
data: {id:id},
success: function(data) {
console.log('Succes!',data);
},
error : function(err) {
console.log('Error!', err);
},
});
});
DocumentiController.php:
/**
* Selzionare files in base all'id della cartella
*/
public function selectFiles(Request $request){
try{
$id = $request->id;
$files = \App\Documento::where('cartella_id',$id)->get();
return response()->json(compact('files'));
}
catch(\Exception $e){
echo json_encode($e->getMessage());
}
}
Route:
Route::post('archivio_documenti/{id}/selectFiles', 'DocumentiController#selectFiles');
Update:
#foreach($files as $key => $file)
<div id="myDIV" class="file-box">
<div class="file">
{!! Form::open(['method' => 'DELETE','route' => ['documento.destroy', $file->id]]) !!}
<button type="submit" class="#" style="background: none; border: none; color: red;">
<i class='fa fa-trash' aria-hidden='true'></i>
</button>
{!! Form::close() !!}
<i class='fa fa-edit' aria-hidden='true'></i>
<input id="myInput_{{$key}}" type="text" value="{{'project.dev/'.$file->path.'/'.$file->file}}">
<i class="btnFiles fa fa-files-o" aria-hidden="true" data-id="{{$key}}"></i>
<a href="{{' http://project.dev/'.$file->path.'/'.$file->file}}">
<span class="corner"></span>
<div class="icon">
<i class="img-responsive fa fa-{{$file->tipo_file}}" style="color:{{$file->color_file}}"></i>
</div>
<div class="file-name">
{{$file->file}}
<br>
<small>Update: {{$file->updated_at}}</small>
</div>
</a>
</div>
</div>
#endforeach
OK, the foreach of yours is a bit complex, but the idea itself is simple: recreate the foreach loop from your Blade in Javascript and append the result to the DOM.
In your success callback you could e.g. do this:
$('#treeview').on("select_node.jstree", function (e, data) {
var id = data.node.id;
$.ajax({
type: 'POST',
url: 'archivio_documenti/+id+/selectFiles',
data: {id:id},
success: function(data) {
// Build the HTML based on the files data
var html = '';
$.each(data, function(i, file) {
html += '<div class="file" id="file_' + file.id + '">' + file.updated_at + '</div>';
});
// Append the built HTML to a DOM element of your choice
$('#myFilesContainer').empty().append(html);
},
error : function(err) {
console.log('Error!', err);
},
});
});
Obviously, this is simplified and you'd need to use the HTML structure you've shown us in the foreach loop above, but the idea is the same: (1) loop through your files in the data object and build the HTML structure row by row, (2) put the whole HTML block in the DOM, wherever you need it to be displayed after the user clicked on a folder.
Alternative:
If you'd like to keep the foreach loop in Blade instead of of Javascipt, you could move the loop to a separate blade:
folder_contents.blade.php
#foreach($files as $key => $file)
<div id="myDIV" class="file-box">
<div class="file">
{!! Form::open(['method' => 'DELETE','route' => ['documento.destroy', $file->id]]) !!}
<button type="submit" class="#" style="background: none; border: none; color: red;">
<i class='fa fa-trash' aria-hidden='true'></i>
</button>
{!! Form::close() !!}
<i class='fa fa-edit' aria-hidden='true'></i>
<input id="myInput_{{$key}}" type="text" value="{{'project.dev/'.$file->path.'/'.$file->file}}">
<i class="btnFiles fa fa-files-o" aria-hidden="true" data-id="{{$key}}"></i>
<a href="{{' http://project.dev/'.$file->path.'/'.$file->file}}">
<span class="corner"></span>
<div class="icon">
<i class="img-responsive fa fa-{{$file->tipo_file}}" style="color:{{$file->color_file}}"></i>
</div>
<div class="file-name">
{{$file->file}}
<br>
<small>Update: {{$file->updated_at}}</small>
</div>
</a>
</div>
</div>
#endforeach
Then, in your controller:
public function selectFiles(Request $request){
try{
$id = $request->id;
$files = \App\Documento::where('cartella_id',$id)->get();
// Save the view as string
$view = view('folder_contents.blade.php', compact('files')))->render();
// Pass the ready HTML back to Javasctipt
return response()->json(compact('view'));
}
catch(\Exception $e){
echo json_encode($e->getMessage());
}
}
you must set header for ajax
headers: {
'X_CSRF_TOKEN':'xxxxxxxxxxxxxxxxxxxx',
'Content-Type':'application/json'
},
and in Controller
public function selectFiles(Request $request){
try{
$id = $request->id;
$files = \App\Documento::where('cartella_id',$id)->get();
return response()->json($files);
}
catch(\Exception $e){
echo json_encode($e->getMessage());
}
}

Deleting image on laravel from storage

can someone please help me with this?
I have this code on controller:
public function deleteImage($element, $id){
if($element != null && $id != null){
Storage::disk('public')->deleteDirectory('/images/'.$element. '/'. $id);
}
}
And I have this on the blade:
<script>
$('.delete_image').click(function(){
var img= $('#pro_img').attr("src");
alert(img); // here is showing this myapp/public/images/questions/459/medium/11d487e5cdbde68dde65b4f396e67859
$.ajax({
type: "GET",
url: '/deleteImage',
data: {'img':img},
success: function(data){
console.log("ajaxdata",data);
}
});
});
</script>
And I also have the button
<button type="button" value="{{-- {{ $i }} --}}" class="btn btn-flat btn-default btn-sm delete_image" id="delete_image" title="#lang('buttons.remove_option')"><i class="fa fa-trash-o" aria-hidden="true"></i> </button>
And the img:
<img src="{{url('/')}}/images/questions/{{ $question->id }}/medium/{{ $question->question_image }}" class="answer-image-create" id="pro_img">
I need to do when I click the button delete the image, can anyone help me please what I am doing wrong here?
use delete() instead of deleteDirectory() . For example,
Storage::disk('public')->delete($image_url);
Instead of Storage::disk('public')->deleteDirectory('/images/'.$element. '/'. $id); use Storage::disk('public')->delete('/images/'.$element. '/'. $id);
The first one is used to delete and entire directory.
Also, I don't see you passing the second parameter ($id). In that case, the code inside the block won't run at all. If you need the ID, please send it with the request as well.

Resources