I'm new to both symfony and ajax , i want to submit a form without refreshing the page everytime i was following along with this tutorial , everything working the page does submit to the database but the problem is that i get this message in the browser
{"message":"Success!"}
This is what i have in my controller .
$bon = new Bons();
$form = $this->createForm('AppBundle\Form\BonsType', $bon);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($bon);
$em->flush();
return new JsonResponse(array('message' => 'Success!'), 200);
}
return $this->render('bons/new.html.twig', array(
'bon' => $bon,
'form' => $form->createView(),
));
The ajax part :
$(document).ready(function() {
$('body').on('submit', '.myForm', function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize()
})
.done(function (data) {
if (typeof data.message !== 'undefined') {
alert(data.message);
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (typeof jqXHR.responseJSON !== 'undefined') {
if (jqXHR.responseJSON.hasOwnProperty('form')) {
$('#form_body').html(jqXHR.responseJSON.form);
}
$('.form_error').html(jqXHR.responseJSON.message);
} else {
alert(errorThrown);
}
});
});
});
is there any way to submit the form without redirecting or refreshing the page