hello I'm looking for a script that could allow me to delete item in a symfony project using ajax, I didn't find any solution for this I tried to delete an item via id (I gave a static id) and then get the result without refreshing the page
here is my controller
$em = $this->getDoctrine()->getManager();
$evenement = $em->getRepository("TunisiaMallBundle:Evenement")->find(39);
$em->remove($evenement);
$em->flush();
$evenements = $em->getRepository("TunisiaMallBundle:Evenement")->findAll();
$response = new Response();
$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($evenements));
return $response;
In your twig put something like this :
<button class="deleteBtn" id="{{ item.id }}">Remove</button>
Here is the ajax using JQuery :
$(document).ready(function(){
$('.deleteBtn').click(function (e) {
e.preventDefault();
itemId = $(this).attr('id');
$.ajax({
url: frm.attr('action'),
data: {'entityId':itemId},
method: 'post',
success: function (data, reponse) {
if(reponse == 'good' ){
//appear pop to say success blabla
}
},
error: function () {
//appear pop to say error blabla
},
});
});
And the Controller :
public function ajaxDeleteItemAction(Request $request)
{
if($request->isXmlHttpRequest()){
$id = $request->get('entityId');
$em = $this->getDoctrine()->getManager();
$evenement = $em->getRepository("TunisiaMallBundle:Evenement")-
>find($id);
$em->remove($evenement);
$em->flush();
return new JsonResponse('good');
}
}