Symfony2: The CSRF token is invalid. Please try to resubmit the form

前端 未结 1 1050
傲寒
傲寒 2020-12-20 03:04

I have a form wher I have to fill in some information in a field. Even if I put something inside, I am getting the error:

The CSRF token is invalid. Please t         


        
相关标签:
1条回答
  • 2020-12-20 03:48

    Send a serialized form using the serialize jQuery method:

    $form.submit(function (e) {
        e.preventDefault();
    
        $this = $(this);
        $.post($this.attr('action'), $this.serialize(), function (response) {
            // handle the response here
        });
    });
    

    This way Symfony will handle the submit request as a normal request — you don't have to do anything special to handle an Ajax form submission. All you'll need to do is to return a JsonResponse — if you need it, of course.

    Here is an example of handling the form — adapt it to your needs:

    if ('POST' === $request->getMethod()) {
        $form->bind($request);
    
        if ($form->isValid()) {
            // do something here — like persisting or updating an entity
    
            return new JsonResponse([
                'success' => true,
            ]);
        }
    
        return new JsonResponse([
            'success' => false,
            'form' => $this->render($pathToTheTemplateHere, [
                'form' => $form,
            ],
        ]);
    }
    

    The other way would be to use different templates: form.json.twig and form.html.twig — read the docs for details.

    0 讨论(0)
提交回复
热议问题