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 resp
With symfony 3 and the error validator you can parse your Ajax request like this:
/**
* Create new student (ajax call)
* @Method("POST")
* @Route("/student/create", name"student_create")
* @param Request $request
* @return JsonResponse
*/
public function createAction(Request $request)
{
$student = new Student();
$form = $this->createForm(CreateStudentType::class, $student);
$form->handleRequest($request);
$errors = array();
if ($form->isSubmitted()) {
$validator = $this->get('validator');
$errorsValidator = $validator->validate($student);
foreach ($errorsValidator as $error) {
array_push($errors, $error->getMessage());
}
if (count($errors) == 0) {
$em = $this->getDoctrine()->getManager();
$em->persist($student);
$em->flush();
return new JsonResponse(array(
'code' => 200,
'message' => 'student toegevoegd',
'errors' => array('errors' => array(''))),
200);
}
}
return new JsonResponse(array(
'code' => 400,
'message' => 'error',
'errors' => array('errors' => $errors)),
400);
}
And jquery ajax
$("#createForm").submit(function(e) {
e.preventDefault();
var formSerialize = $(this).serialize();
var url = location.origin + '/web/app_dev.php/student/create';
$.ajax({
type: "POST",
url: url,
data: formSerialize,
success: function (result) {
console.log(result);
if (result.code === 200) {
// refresh current url to see student
} else {
}
}
});
});