title: Form Validation in symfony from ajax call
body: <p>I need to store data from a form with symfony through an ajax call me not to update the browser. Also I need you in case of errors in the fields can somehow get them in response to that call Ajax and to show my form errors, all without refreshing the page.</p>
  
  <p>I have a form with symfony asset to validate fields, and make everything perfect if ajax call is performed, stores the data or updates the page showing errors, but I need that same without refreshing the page.</p>
  
  <p>Then I put some of the code I'm using:</p>
  
  <p>Controller:          </p>
  
  <pre><code>public function createAction(Request $request)
  {
      $entity = new Student();
      $form = $this-&gt;createCreateForm($entity);
      $form-&gt;handleRequest($request);
  
      if ($form-&gt;isValid()) {
          $em = $this-&gt;getDoctrine()-&gt;getManager();
          $em-&gt;persist($entity);
          $em-&gt;flush();
  
          return $this-&gt;redirect($this-&gt;generateUrl('student_show', array('id' =&gt; $entity-&gt;getId())));
      }
  
      return $this-&gt;render('BackendBundle:Student:new.html.twig', array(
          'entity' =&gt; $entity,
          'form'   =&gt; $form-&gt;createView(),
      ));
  }
  </code></pre>
  
  <p>ajax call:<strong>(I do not understand how to handle the error part)</strong></p>
  
  <pre><code>$('.form_student').submit(function(event) {
     event.preventDefault();
  
    $.ajax({
      type: 'POST',
      url: Routing.generate('student_create'),
      data: $(this).serialize(),
  
      success: function(data) {
  
        //clean form
        cleanForm($(this));
  
        //show success message
        $('#result').html("&lt;div id='message'&gt;&lt;/div&gt;");
        $('#message').html("&lt;h2&gt; student created&lt;/h2&gt;").hide();
        $('#message').fadeIn('slow').delay(5000).fadeOut('slow');
        event.stopPropagation();   
      },
      error: function (xhr, desc, err) 
        {
          alert("error");
        }
      })
    return false;
  });
  </code></pre>
  
  <p>I've seen some return a JsonResponse from the controller and use Ajax, but I'm starting with Ajax and I do not know how to use it. Then I put the code I mean:</p>
  
  <pre><code> if ( $request-&gt;isXmlHttpRequest() ) {
  
      if ($form-&gt;isValid()) {
       //...
       return new JsonResponse(array('message' =&gt; 'Success!'), 200);
      }
  
      $response = new JsonResponse(array(
      'message' =&gt; 'Error',
      'form' =&gt; $this-&gt;renderView('BackendBundle:student:new.html.twig',
              array(
          'entity' =&gt; $entity,
          'form' =&gt; $form-&gt;createView(),
      ))), 400);
  
    return $response;
  }
  </code></pre>
  
  <p>If you could help me understand more how to use Ajax to solve this problem, I eternally grateful, because for many manuals I've seen I still do not understand it well.</p>
  
  <p>Thank you very much in advance.</p>