0

I have a list of animals profiles (ID cards). When I click on one of them while logged in as an Admin, I access a page with more details and several pictures. There, I can edit the animal profile (POST method), and I would also like to be able to delete a picture by clicking on it. I'm trying to use Ajax to do that, but I'm unable to complete the process. My code so far :

Route::get('/edition-adoption/{animal}', 'AnimalsController@editAdoption')
    ->where('animal', '[0-9]+');

Route::post('/edition-adoption/{animal}', 'AnimalsController@updateAdoption');

Route::get('/edition-adoption/{folder}/{file}/delete', ['uses' => 'AnimalsController@deletePicture', 'as' => 'delete']);

View :

<form role="form" method="POST" enctype="multipart/form-data" action="{{ url('/edition-adoption/{animal}') }} ">
        {{ csrf_field() }}

 /*several fields to update*/

            <div class="col-xs-11">
                <?php
                    edit_profile($animal->id);
                ?>
                <script src={{asset("/js/imageSrc.js")}}></script>
            </div> 
     /*other fields & submit button*/ </form>

Controller :

public function editAdoption (Animal $animal) {
    return view('administration/edition-adoption',['animal' => $animal]);
}

public function deletePicture($file, $folder) {
    $path = public_path('js/slider_images/Adoption/Profile/'.$folder.'/'.$file);
    unlink($path);
}

public function updateAdoption (Request $request) {
    /*several update requests*/
}

Helper :

function edit_profile($current_id) {


            $paths = File::Files('js/slider_images/Adoption/Profile/'.$current_id);

       if (count($paths)==0) {
        echo 
        "<p>Aucune image</p>";
       }    
           else {
        foreach($paths as $path)
                {
                $filesinfo[] = pathinfo($path);
                }

               foreach ($filesinfo as $file) {

                $current_basename = $file['basename'];

                echo 
                "<img onclick='getImgSrc(this)' width='200px' src='".asset("/js/slider_images/Adoption/Profile/".$current_id."/".$current_basename)."'/>&nbsp&nbsp";
                }
       }
}

imageSrc.js (Ajax) :

    function getImgSrc(param){

var imgSrc = $(param).attr("src");
var myarr = imgSrc.split("/");
var arrlen = myarr.length;
var id = myarr[arrlen-2];
var myvar = myarr[arrlen-1];
var result = confirm("Voulez-vous vraiment supprimer cette image ? Cette action est irréversible.");

if (result) {

    $.ajax({
          url: 'delete',
          headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
          data: {'folder': id, 'file' : myvar},
          success: function (response) {
             alert('Image supprimée !');
          },
          error: function () {
             alert('Erreur. Veuillez réessayer.');
          }
        });
    }
}

The confirmation alert works fine, but when I click on OK, the following exception appear :

GET http://localhost/sites/(...)/public/edition-adoption/delete?folder=foldername&file=filename.jpg 405 (Method Not Allowed)

Any idea(s) on how to solve this problem?

7
  • Try passing the full relative url in your ajax. Your route is /edition-adoption/{folder}/{file}/delete', but it's accessing /edition-adoption/delete?
    – aynber
    Commented Mar 2, 2017 at 15:33
  • @aynber thank you for your answer. I tried using url: id+'/'+myvar+'/delete', but the result is the same...
    – Mefimefi
    Commented Mar 2, 2017 at 15:47
  • check what your artisan route:list | grep edition-adoption | grep delete says.
    – Alex Blex
    Commented Mar 2, 2017 at 15:57
  • @AlexBlex : $ php artisan route:list | grep edition-adoption | grep delete gives me the following lines : | | GET|HEAD | edition-adoption/{folder}/{file}/delete | delete | App\Http\Controllers\AnimalsController@deletePicture | web |
    – Mefimefi
    Commented Mar 2, 2017 at 16:32
  • Cool, so curl http://localhost/sites/(...)/public/edition-adoption/foldername/filename.jpg/delete -v 2>&1 | head -20 should delete the image. Could you confirm if it returns 405 response ?
    – Alex Blex
    Commented Mar 2, 2017 at 16:55

1 Answer 1

0

Finally solved it thanks to a friend. It appears the order of the parameters ($folder, $file) in the Controller mattered. They were in the expected order for the url/route (/edition-adoption/{folder}/{file}/delete), BUT they were swapped in the path (I expected http://localhost/sites/(...)/public/edition-adoption/foldern‌​ame/filename.jpg/del‌​ete and got http://localhost/sites/(...)/public/edition-adoption/filen‌​ame.jpg/foldername/del‌​ete; which explained the 404 error). I changed public function deletePicture($file, $folder) to public function deletePicture($folder, $file) and now it works fine! I also added $(param).hide(); in the Ajax success to hide the deleted picture without having to refresh the page. Anyway, thanks to @aynber and @AlexBlex for their advice!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.