Symfony2: токен CSRF недопустим. Попробуйте повторно отправить форму

У меня есть форма, в которой я должен заполнить некоторую информацию в поле. Даже если я что-то вложил внутрь, я получаю сообщение об ошибке:

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

В связи с этим вопросом: symfony2 CSRF недействителен Я правильно использую $ form-> bindRequest ()

 if ($this->getRequest()->getMethod() == 'POST') { $form->bindRequest($this->getRequest()); if ($form->isValid()) { ... } 

Вот мой шаблон (веточка):

 <div class="item item-last"> <h1>Create Affiliation</h1> {% if valid == false %} <div class="error"> {{ form_errors(form) }} {{ form_errors(form.affiliation) }} {{ error }} </div> {% endif %} {% if app.session.flash('user-notice') != '' %} <div class="flash-notice"> {% autoescape false %} {{ app.session.flash('user-notice') }} {% endautoescape %} </div> {% endif %} </div> <div class="item item-last"> <form action="{{ path('SciForumVersion2Bundle_user_submission_affiliation_create', {'hash_key' : submission.hashkey, 'author_id' : author.id }) }}?ajax=no" method="POST" class="authorForm" {{ form_enctype(form) }}> <div style="float:left;"> <table width="100%" cellspacing="0" cellpadding="0"> <tr> <td> {{ form_label(form.affiliation) }} </td> <td> {{ form_widget(form.affiliation, { 'attr': {'size': 40} }) }} </td> </tr> <tr> <td> &nbsp; </td> <td> <div class="button button-left button-cancel"> <img src="{{ asset('bundles/sciforumversion2/images/design/new/button-red.png') }}"/> <a href="{{ path('SciForumVersion2Bundle_user_submission_author_edit', { 'hash_key' : submission.hashkey, 'author_id' : 0 }) }}" class="submission_link">cancel</a> </div> <div style="float: left;">&nbsp;</div> <div class="button button-left button-cancel"> <img src="{{ asset('bundles/sciforumversion2/images/design/new/button.png') }}"/> <input type="submit" name="login" value="submit" /> </div> <div style="clear: both;"></div> </td> </tr> </table> </div> {{ form_rest(form) }} </form> </div> 

И вот код js:

 function init_submission_functions() { init_fck(); $(".submission_link").unbind("click").bind("click", function() { var href = $(this).attr("href"); if( href == null || href == '' ) return false; $.ajax({ type: "POST", async: true, url: href, cache: false, dataType: "json", success: function(data) { $("#content .contentwrap .itemwrap").html( data.content ); init_submission_functions(); } }); return false; }); $(".authorForm").unbind("submit").bind("submit", function() { var href = $(this).attr("action"); if( href == null || href == '' ) return false; var affiliation = "blabla"; $.ajax({ type: "POST", async: true, url: href, affiliation: affiliation, cache: false, dataType: "json", success: function(data) { $("#content .contentwrap .itemwrap").html( data.content ); init_submission_functions(); } }); return false; }); } 

Но я все равно получаю ту же ошибку.

Отправьте сериализованную форму, используя метод serialize jQuery :

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

Таким образом, Symfony будет обрабатывать запрос отправки как обычный запрос – вам не нужно делать ничего особенного для обработки формы Ajax. Все, что вам нужно сделать, это вернуть JsonResponse – если вам это нужно, конечно.

Вот пример обработки формы – адаптируйте ее к вашим потребностям:

 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, ], ]); } 

Другой способ – использовать различные шаблоны: form.json.twig и form.html.twig – прочитайте документы для получения более подробной информации.