I've a function in my Symfony2 controller called through Ajax from the view. This is the code on the controller side (a example not the real):
public function addFabAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$response['success'] = TRUE;
if ($request->isXmlHttpRequest()) {
$entity = new Entity();
$form = $this->createForm(new EntityForm(), $entity);
$form->handleRequest($request);
if ($form->isValid()) {
try {
$em->persist($entity);
$em->flush();
$response['entities'] = array();
$dataResponse = array();
$dataResponse['colOne'] = $$entity->getColumnOne();
$dataResponse['colTwo'] = $$entity->getColumnTwo();
$response['entities'][] = $dataResponse;
} catch (Exception $ex) {
$response['success'] = FALSE;
}
} else {
// Response for go through .fail() callback in Ajax request
}
return new JsonResponse($response);
}
}
Then in the view I call on some event as follow:
$.post(Routing.generate('addFab'), $form.serialize(), 'json').done(function (data, textStatus, jqXHR) {
// if all goes fine then show messages and much more
}
}).fail(function () {
// if something goes wrong then show and alert and try to show info to the user
return false;
}).always();
Now if $form->isValid()
is TRUE or not the request always be made and therefore will go through .done()
callback so I need to return something, not clear what, if form isn't valid so response goes through .fail()
callback, otherwise I'll always need to check if, for example, $response['success']
is TRUE or FALSE in the .done()
callback and forget about the .fail()
which seem wrong to me. I don't now if the right way is to return an exception using the HttpFoundation Componente or something else so any advice? What's the best way to get ride of this?
fail(function (jqXHR, status, error) { alert(status+':' + error) // if something goes wrong then show and alert and try to show info to the user return false; })
- it could be that the response is not properly formatted and you are getting a parse error – Arun P Johny<?php http_response_code(400); ?>
– Arun P Johny