I want to do a comment system in AJAX with symfony (2.8) and unfortunately, for the moment, i can't even get past the '$isAjax = $request->isXmlHttpRequest();'
I'm sorry if the code isn't 100% clean, i'm and testing a lot of things at this point.
here's a snippet of my controller:
public function showCommentsAction($id)
{
$request = $this->container->get('request');
$em = $this->getDoctrine()->getManager();
$event = $em->getRepository('MainBundle:Events')->find($id);
$comments = $em->getRepository('MainBundle:Comments')->find($id);
$user = $this->get('security.token_storage')->getToken()->getUser();
$comment = new Comments();
$comment->setEvent($event);
$comment->setDateComment(new \DateTime("now"));
$form = $this->get('form.factory')->createBuilder('form', $comment)
->add('comment')
->getForm();
$isAjax = $request->isXmlHttpRequest();
var_dump($isAjax);
if ($request->isXmlHttpRequest()) {
$form->handleRequest($request);
// On vérifie que les valeurs entrées sont correctes
// (Nous verrons la validation des objets en détail dans le prochain chapitre)
if ($form->isValid()) {
// On l'enregistre notre objet $advert dans la base de données, par exemple
$em = $this->getDoctrine()->getManager();
$em->persist($comment);
$em->flush();
return $this->redirect($request->getUri('event'));
}
}
return $this->render('MainBundle:Default:Events\event.html.twig',array("event"=> $event,'form'=>$form->createView()));
here's my js :
$(document).ready(function() {
// Au submit du formulaire
$('#form').submit(function () {
// On fait l'appel Ajax
$.ajax({
type: "POST",
url: "{{ path('showcomments'}}",
//data: {commentaire: commentaire, _csrf_token: "{{ csrf_token('authenticate') }}"},
cache: false,
data: {event_id: event_id},
success: function (data) {
alert('succes');
}
});
// On retourne false pour ne pas recharger la page
return false;
});
});
my route :
showcomments:
path: /showcomments/{id}
defaults: { _controller: MainBundle:Comments:showcomments }
methods: POST
and my form :
<li class="write-new">
<form action="{{ path('showcomments', {'id' : event_id}) }}" method="POST" {{ form_enctype(form) }} id="form">
{{ form_widget(form) }}
<input type="submit" />
</form>
</li>