Token CSRF Symfony

0

I am sending a request by ajax to a controller and this error is generated

  

ERROR: The CSRF token is not valid. Please try to send the form again.

Form

{{ form_start(form, {'action': path_with_locale('general_alerts'), 'attr':{'id': 'form_alert1'} }) }}
                        {% if app.user %}
                            {{ form_widget(form.email, { 'attr': {'value': app.user.username, 'class': 'hide'} }) }}
                        {% else %}
                            <div class="form-group" style="text-align:left;">
                                {{ form_errors(form.email, { 'alert_attr': {'class': 'alert alert-danger'} }) }}
                                {{ form_label(form.email, 'Email :', { 'label_attr': {'class': 'control-label'} }) }} 
                                {{ form_widget(form.email, { 'attr': {'class': 'text-input', 'placeholder': "Email"} }) }}
                            </div>
                        {% endif %}    
                        {{ form_widget(form.url, { 'attr': {'value': ajaxUrl, 'class': 'hide'} }) }}
                        <div style="text-align: right">
                            <button type="submit" class="btn btn-success"> Crear alerta</button>            
                        </div>
                    {{ form_rest(form) }}
                    {{ form_end(form) }}

Ajax

jQuery("#form_alert1").submit(function (e) {
            e.preventDefault();
            var $url = $(this).attr('action');
            var $data = $(this).serialize();
            $.ajax({
                type: "POST",
                url: $url,
                data: $data
            }).done(function (result) {
                if (result.success) {
                    $('#result').html('<p>Tu alerta se ha guardado exitosamente. </p>');
                } else if (result.fail) {                        
                    $('#result').html('<p>Ya tienes creada una alerta para esta búsqueda. </p>');                        
                }
            });
        });

Controller

public function alertAction(Request $request) {
    $alert = new Alerts();
    $form = $this->createForm(new AlertsType(), $alert);


    if ($request->getMethod() == 'POST') {
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            if ($request->isXmlHttpRequest()) {
                    $alert->setEntrydate(new \DateTime());
                    $alert->setPrice("011000");
                    $alert->setState(1);
                    $em->persist($alert);
                    $em->flush();
                    $response = new Response();
                    $output = array('success' => true);
                    $response->headers->set('Content-Type', 'application/json');
                    $response->setContent(json_encode($output));
                    return $response;

            } 
        } 
    }
    
asked by Lina Cortés 23.01.2018 в 23:18
source

2 answers

1

If you do not want to have CSRF token security enabled in your forms, you can disable it in your config.yml file:

framework: csrf_protection: enabled: false

    
answered by 28.02.2018 / 17:06
source
0

The error indicates that you are not sending the token that goes in a hidden input inside the form, you should try to move the button at the end of the form like this:

{{ form_start(form, {'action': path_with_locale('general_alerts'), 'attr':{'id': 'form_alert1'} }) }}
                    {% if app.user %}
                        {{ form_widget(form.email, { 'attr': {'value': app.user.username, 'class': 'hide'} }) }}
                    {% else %}
                        <div class="form-group" style="text-align:left;">
                            {{ form_errors(form.email, { 'alert_attr': {'class': 'alert alert-danger'} }) }}
                            {{ form_label(form.email, 'Email :', { 'label_attr': {'class': 'control-label'} }) }} 
                            {{ form_widget(form.email, { 'attr': {'class': 'text-input', 'placeholder': "Email"} }) }}
                        </div>
                    {% endif %}    
                    {{ form_widget(form.url, { 'attr': {'value': ajaxUrl, 'class': 'hide'} }) }}
                {{ form_rest(form) }}
                {{ form_end(form) }}
                    <div style="text-align: right">
                        <button type="submit" class="btn btn-success"> Crear alerta</button>            
                    </div>
    
answered by 28.02.2018 в 17:11