You need to handle the XMLHttpRequests differently to your regular HTML requests.
At present when an XMLHttpRequest is made but the form fails the whole page is rendered again (with a "success" status code), but you only want to return a response with a message and a "failed" status code.
The following should help you.
public function createAction(Request $request)
{
// if request is XmlHttpRequest (AJAX) but not a POSt, throw an exception
if ($request->isXmlHttpRequest() && !$request->isMethod(Request::METHOD_POST)) {
throw new HttpException('XMLHttpRequests/AJAX calls must be POSTed');
}
$entity = new Student();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
// if the form was successful and the call was an AJAX request
// respond with a JSON Response (with a 201/created status code)
if ($request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'Success!'), 201);
}
// If the form was successful and the call was HTTP
// redirect to "show student"
return $this->redirect('student_show', array('id' => $entity->getId()));
}
// if request was an AJAX call and (obviously) the form was not valid
// return message about form failure
// (with a 400/Bad Request status code)
if ($request->isMethod(Request::METHOD_POST)) {
return new JsonResponse(array('message' => 'failed due to form errors'), 400);
// you could also loop through the form errors to create an array, use a custom
// form -> errors array transformer or use the @fos_rest.view_handler to output
// your form errors
}
return $this->render('BackendBundle:Student:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
Updated
The javascript should work like this.
$('.form_student').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: Routing.generate('student_create'),
data: $(this).serialize(),
dataType: 'json',
// if "student_create" returns a 2** status code
success: function(response) {
// should return "Success!"
alert(response.message);
},
// if "student_create" returns a non-2** status code
error: function (xhr, desc, err){
// if the response was parsed to json and has a message key
if (xhr.responseJSON && xhr.responseJSON.message) {
alert(xhr.responseJSON.message);
// otherwise use the status text
} else {
alert(desc);
}
}
});
return false;
});