简体   繁体   中英

How to redirect after a delete with Symfony and js

I am trying to refresh the page with js , after a delete , but I can not find the mistake. I am working with Symfony 4.

If someone can see where my mistake is it would be really great. :)

This is my Controller :

 /// SUPPRIMER UNE VIDEO ///

/**
 * @Route("/supprimerVideo/{id}", name="deleteVideo")
 * @Method({"DELETE"})
 * @param Request $request
 * @param $id
 * @return \Symfony\Component\HttpFoundation\RedirectResponse
 */
public function deleteVideo(Request $request, $id){

    $mediaVideo = $this->getDoctrine()->getRepository(MediaVideo::class)->find($id);

    $entityManager = $this->getDoctrine()->getManager();
    $entityManager->remove($mediaVideo);
    $entityManager->flush();

    $response = new Response();
    $response->send();
}}

This is my js file :

 const videos = document.getElementById('videos'); if (videos){ videos.addEventListener('click', e => { if(e.target.className === 'btn btn-danger delete-item'){ if (confirm('Es-tu sur de vouloir supprimer ?')) { const id = e.target.getAttribute('data-id'); fetch('/supprimerVideo/${id}', { method: 'DELETE' }).then(res => window.location.reload()); } } }); } 

This is my twig file :

 <div class="col-12" id="videos"> <a href="#" class="btn btn-danger delete-item" data-id="{{video.id}}">Delete</a> </div> 

And I added the script in the base.html.twig too .

Replace quotes in fetch('/supprimerVideo/${id}', { with backticks:

const id = 123;
console.log('/supprimerVideo/${id}')
/supprimerVideo/${id}
console.log(`/supprimerVideo/${id}`)
/supprimerVideo/123

You are using Template literals ${} that are not replaced with actual id value. Inspect your request in debug toolbar to see if you are really calling correct url in your symfony application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM