I am sending an ajax request to a controller and it generates this error
ERROR: The CSRF token is not valid. Please try submitting 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;
}
}
}
If you don't want to have CSRF token security enabled in your forms, you can disable it in your config.yml file:
framework: csrf_protection: enabled: false
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 to the bottom of the form like this:
To fix this you should use this on the form in the twig part:
This way the error is no longer displayed and you have this security check which is very important. I tried it on
symfony 4
and it works perfect