1

I have a form type that uses a twig template and in that twig, I get the images attached to the current listing object and display them along with an option to delete them for the user. I'd like to be able to have it where the user can delete the images individually without the page refreshing so I'm trying to trigger the controller method using Ajax.

scripts.js

$('.delete_image').on('click', function(e) {
  $.ajax({
    type: 'POST',
    url: '/delete_image',
    data: ({
      listing_id: $('#listing_id').val(),
      imageName: 'nature-forest-trees-158251.jpg'
    }),
    success: function(response) {},

    error: function(jqXHR, textStatus, errorThrown) {
      alert('status code: ' + jqXHR.status + 'errorThrown: ' + errorThrown + 'jqXHR.responseText:' + jqXHR.responseText);
    }
  })
})

imageName is just a placeholder value (of the image I'm debugging) and in my controller I have

ListingController.php

/**
 * @Route("/delete_image", name="delete_image")
 * @Method({"GET", "POST"})
 * @ParamConverter("listing", class="DirectoryPlatform\AppBundle\Entity\Listing")
 */
public function deleteImage(Request $request, Listing $listing) {
  // $listing_id = (isset($_POST['listing'])) ? $_POST['listing'] : -1;
  // $imageName = (isset($_POST['imageName'])) ? $_POST['imagename'] : -1;
  $listing_id = $request->get('listing');
  $imageName = $request->get('imageName');
  $this->get('punk_ave.file_uploader')->removeFiles(array('folder' => 'tmp/attachments/' . $listing->getId() . '/'. $imageName));

  exit(0);
}

I've tried using $_POST[] as well as $request->get() to no avail. I could maybe use inline scripting but it's something I want to avoid for the sake of best coding practices.

1 Answer 1

2

The way to get POST variables inside a controller is:

$listing_id = $request->request->get('listing');

However in your case I would be sceptical if I should use AJAX requests in the sense that you could avoid the overhead of AJAX calls, by manipulating properly the DOM (remove for example an image from the DOM when delete button clicked, without taking any action at the server) and finally submit all the changes together by submitted your form and then remove the deleted images from your entity.

This last call could as well be an AJAX call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.