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.
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.
Then I put some of the code I'm using:
Controller:
public function createAction(Request $request)
{
$entity = new Student();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('student_show', array('id' => $entity->getId())));
}
return $this->render('BackendBundle:Student:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
ajax call:(I do not understand how to handle the error part)
$('.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("<div id='message'></div>");
$('#message').html("<h2> student created</h2>").hide();
$('#message').fadeIn('slow').delay(5000).fadeOut('slow');
event.stopPropagation();
},
error: function (xhr, desc, err)
{
alert("error");
}
})
return false;
});
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:
if ( $request->isXmlHttpRequest() ) {
if ($form->isValid()) {
//...
return new JsonResponse(array('message' => 'Success!'), 200);
}
$response = new JsonResponse(array(
'message' => 'Error',
'form' => $this->renderView('BackendBundle:student:new.html.twig',
array(
'entity' => $entity,
'form' => $form->createView(),
))), 400);
return $response;
}
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.
Thank you very much in advance.
See Question&Answers more detail:
os