0

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>

Devine
  • 11
  • 3
  • when you say 'cant get past', do you mean its failing the if condition check? – DevDonkey Apr 17 '17 at 15:36
  • yes, indeed, i got this : 'src\Main\MainBundle\Controller\CommentsController.php:32:boolean false' – Devine Apr 17 '17 at 15:39
  • inspect the headers in the request, do they contain `X-Requested-With`? because thats all `isXmlHttpRequest` checks for. `var_dump($request->headers->all())` – DevDonkey Apr 17 '17 at 15:42
  • no, the vardump doesn't feature 'X-Requested-With' – Devine Apr 17 '17 at 15:49
  • Possible duplicate of [Cross-Domain AJAX doesn't send X-Requested-With header](http://stackoverflow.com/questions/8163703/cross-domain-ajax-doesnt-send-x-requested-with-header) – DevDonkey Apr 17 '17 at 15:54
  • i tried to add, the header, and crossdomain parameters, still no X-Requested-With in the var dump and still fails the isAjax – Devine Apr 17 '17 at 16:00
  • Just pass a query parameter in the ajax call, that you can check for – john Smith Apr 17 '17 at 17:31
  • What do you mean by that? (sorry if the question sound stupid) – Devine Apr 17 '17 at 18:16

1 Answers1

0

you pass /showcomments/{id} {id} in ajax data. And according to your route, it is a parameter. Try url: "{{ path('showcomments',{'id': yourId})}}", first try yourId just with hardcode, should be like you put in your form. So you can use url straight from your form also. Dont forget to preventDefault on submit. To check if your ajax works you should do like this:

return new Response($id);

and in js

success(data){console.log(data)}

And basically, you do not need to $event = $em->getRepository('MainBundle:Events')->find($id);

if you do

showCommentsAction(Event $event)

it will find automatically.

$comment->setDateComment(new \DateTime("now"));

this line can be done in controller of your Entity and you do not need to pass "now".

Dima Rashevskiy
  • 182
  • 1
  • 1
  • 15