2

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 try to resubmit the form

Related to this question: symfony2 CSRF invalid I am using correctly the $form->bindRequest()

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

Here is my template (twig) code:

<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>

And here is the js code:

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

But I am still getting the same error.

Community
  • 1
  • 1
Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265

1 Answers1

8

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.

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
  • Thank you @elnur, but what are data? How can I get the data here? It's an array? Thank you. – Milos Cuculovic Oct 31 '12 at 10:02
  • On the Symfony side, you handle the form like any usual form. – Elnur Abdurrakhimov Oct 31 '12 at 10:04
  • Ok. One more question please, how to return the JsonResponse? the "respone" from the "function (response)" is the jsonResponse ? – Milos Cuculovic Oct 31 '12 at 10:17
  • I have another problem now related to this auestion. What I tryed to do before is that on success (with ajax) I am asigning the returned data to an html element. Now, I am getting a json response I think and I don't kow how to parse the daat I need from. – Milos Cuculovic Nov 01 '12 at 16:00
  • Thank you, here is: http://stackoverflow.com/questions/13191316/symfony2-and-submit-wit-javascript-how-to-get-html-content – Milos Cuculovic Nov 02 '12 at 07:53