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.
Related
Anyone please help me, i have spent an hours to solve this but didn't solve yet. I got an error when i click delete button with checkbox. Below my Route code:
Route::delete('/posts/destroychecked', [App\Http\Controllers\PostController::class, 'destroychecked'])->name('post.destroychecked');
And the following is my controller code:
/* Destroy multiple data */
public function destroychecked(Request $request) {
$ids = $request - > ids;
Post::whereIn('id', explode(",", $ids)) - > delete();
return response() - > json(['success' => "Postingan berhasil dihapus!"]);
}
And then this is my ajax code:
$(function(e) {
$('#deletedAllSelectedRecord').click(function(e) {
e.preventDefault();
var allids = [];
$('input:checkbox[name=ids]:checked').each(function() {
allids.push($(this).val());
});
$.ajax({
url: "{{ route('post.destroychecked') }}",
type: "DELETE",
data: {
_token: $("input[name=_token]").val(),
ids: allids
},
success: function(response) {
$.each(allids, function(key, val) {
$("#sid" + val).remove();
})
}
})
})
})
And this is my index.blade code:
#foreach($posts as $post)
<tr id="sid{{ $post->id }}">
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="ids" name="ids" value="{{ $post->id }}"/>
The following is my button code:
<a href="#" class="btn btn-danger" id="deletedAllSelectedRecord"><i
class="fe fe-trash dropdown-item-icon"></i>{{ __('Hapus Semua') }}</a>
After all that i got error when i click delete button, please help me how to solve this. the following is the error:
DELETE http://upskilling.id/admin/%7B%7B%20route('post.destroychecked')%20%7D%7D 404 (Not Found)
I have a problem with my code. I created upload file with ajax in Laravel. I am using tutorial from here, and yes it is working. But, it working sometimes.
I have no idea where the problem is. But I have changing max_execution_time in php.ini into 0 value. I also included <code>csrf_token()</code> in ajax headers
I wish there somebody help me with this code. I don't know, but the code looks good for me. Here is the code
blade view
<form class="form-main" enctype="multipart/form-data" method="post" id="formbank" >
<div class="field file" data-title="Upload File">
<input type="file" id="myfile" name="myfile" accept="image/*">
<label for="myfile"><i class="fa fa-upload"></i> <span id="file-title">Select File</span></label>
</div>
<div class="field" data-title="Action">
<button class="but-main">Submit</button>
</div>
</form>
JS script
$(document).ready(function(e){
$('#formbank').on('submit',function(e){
e.preventDefault();
var fd = new FormData(this);
fd.append('myfile',$('#myfile')[0].files[0]);
$.ajax({
async: true,
type:'post',
data:fd,
contentType: false,
cache:false,
processData: false,
headers: {
'X-CSRF-TOKEN' : "{{ csrf_token() }}"
},
url: "{{ route('post.bank') }}",
success:function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
});
});
});
post.bank controller
public function createBank(Request $request){
if ($request->hasFile('myfile')) {
$file = $request->file('myfile');
return $file->getClientOriginalName();
}
else {
$text = 'empty';
return $text;
}
In this case, I only try to return name of uploaded file. Here is the result.
https://drive.google.com/file/d/1zK5YmO8f8cGR110X-oi2bTVMiaMCXYi9/view?usp=sharing "result"
Thank you for all suggestion. Many thanks. After several trial and errors, I find a trick to resolve it by calling main function with setTimeOut(). And i put _token validation in controller. When token is empty, it will return a value that let setTimeOut() do the rest of time until token is loaded correctly.
I guess that way is suited for me. And I will be happy if there is a better answer to resolve it in a better way. Thank you anyway..
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>
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 %}
Hi there I am having a problem when I click button delete it deletes the folder with image inside and that is what I want but the page it is not refreshed so I do not know that is deleted till I click refresh
this is the code:
#if($question->question_image)
<img src="{{url('/')}}/images/questions/{{ $question->id }}/medium/{{ $question->question_image }}" class="answer-image-create" id="question_image_box">
<input onchange="readquestionURL(this);" type="file" id="question_file" name="question_image" style="display:none"/>
#else
<img src="{{ asset('noavatars/no-image-selected.png') }}" class="answer-image-create" id="question_image_box">
<input onchange="readquestionURL(this);" type="file" id="question_file" name="question_image" style="display:none"/>
#endif
</div>
{{-- <button type="button" class="btn" id="question_upfile"
style="cursor:pointer; padding-left: 24px; padding-right: 15px;">
<i class="fa fa-upload" aria-hidden="true">
</i>#lang('buttons.upload_image')
</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 javascript code is this:
<script>
$(document).on("click", "button[id=delete_image]", function(data){
var questionid = {{$question->id}};
var element = 'questions';
$.ajax({
type: "POST",
url: "{{ action('website\images\ImagesController#deleteImage') }}",
data: {
_token: "{{ csrf_token() }}",
'id':questionid,
'element' : element,
},
success: function(response) {
console.log(response);
},
error: function(response){
alert("fail");
}
});
function readquestionURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#question_image_box')
.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
});
</script>
The controller is this:
public function deleteImage($element =null, $id = null){
if(request()->ajax()) {
$id = request()->input('id');
$element = request()->input('element');
if($element != null && $id != null){
Storage::disk('public')->deleteDirectory('/images/'.$element. '/'. $id);
}
return 1;
}
}
How can I achieve to delete the image and be refreshed at the same time. Can someone please help me thank you very much .
You can refresh the page using javascript
location.reload();
You'll need to add that line on your ajax's success method.