title: Protect jquery Ajax Requests from CSRF attacks via CSRF token on Symfony 3.4
body: <p>I have the following Symfony Controller:</p>
  
  <pre><code>namespace AppBundle\Controller
  
  use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  use Symfony\Component\HttpFoundation\Request;
  use Symfony\Component\HttpFoundation\JsonResponse;
  
  class MyController extends Controller
  {
    /**
    * @Route("/form", name="get_form")
    * @Method("GET")
    */
    public function getFormAction(Request $request)
    {
      return $this-&gt;render('some_twig.html.twig');
    }
  
    /**
    * @Route("/form_submit", name="submit_form")
    * @Method("POST")
    */
    public function ajaxFormAction(Request $request)
    {
      if($request-&gt;isXmlHttpRequest()){
      return new JsonResponse(['data':"All midori"],JsonResponse::HTTP_OK);
      } else {
       return new JsonResponse(['data':"Echi, hentai, baka"],JsonResponse::HTTP_BAD_REQUEST);
      }
    }
  }
  </code></pre>
  
  <p>The form is submitted via the following javascript code:</p>
  
  <pre><code>$("#someform").on('submit',function(e){
      e.preventDefault();
  
      var self=this; //To avoid Confusion using this
      var url=$(self).attr('action');
  
      $.ajax({
        'method': "POST",
        'url': url,
        'data': $(self).serialize(),
        'statusCode': {
          400: function(data,textStatus,jqXHR) {
            //Handle Error 400
          },
          500: function(data,textStatus,jqXHR){
           //Handle error 500
          }
        },
        'success':function(data){
          //DO some stuff
        }
      });
    })
  </code></pre>
  
  <p>But I have some trouble on how I can protect the Symfony Ajax method from CSRF attacks. When I try to protect via putting CSRF token to form when an aeero occurs eg. an exception thrown it renders my form junk.</p>
  
  <p>Also leaving unprotected is not the best viable option. So how effectively can protect it?</p>