Reputation: 1301
I want to send a Symfony form with AJAX. I already did it but I can't find the error in my code. When I click on Submit, it's sending the form but not with AJAX.
Create form in controller :
$form = $this->createForm(CorrectionReponseQRFormType::class, $passage)->createView();
Twig :
{{ form_start(form, {'id': 'formCorrection'~reponse.id}) }}
{{ form_widget(form.note, {'id': 'note'~reponse.id}) }}
{{ form_widget(form.commentaire, {'id': 'commentaire'~reponse.id}) }}
{{ form_row(form.submit) }}
{{ form_end(form) }}
<script>
var note = document.getElementById("note{{ reponse.id }}").value;
var idCommentaire = 'commentaire{{ reponse.id }}';
var commentaire = CKEDITOR.instances[idCommentaire].getData();
$("#formCorrection{{ reponse.id }}").submit(function() {
$.ajax({
type: "POST",
url: "{{ path('paces_colle_correctioncolleqr_sauvegardercorrectionpassage') }}",
data: {note: note, commentaire: commentaire, idReponse: {{ reponse.id}}}
})
});
</script>
Controller function :
public function sauvegarderCorrectionPassageAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
$em = $this->getDoctrine()->getManager();
$idReponse = $request->request->get('idReponse');
$reponse = $em->getRepository(ReponseQR::class)->find($idReponse);
$note = $request->request->get('note');
$commentaire = $request->request->get('commentaire');
$passerColle = $em->getRepository(PasserColle::class)
->findOneBy(array('colle' => $reponse->getColle()->getId(),
'user' => $reponse->getUser()->getId()));
$reponse->setCorrigee(true);
$passerColle->setNote($note);
$passerColle->setCommentaire($commentaire);
$em->persist($passerColle);
$em->flush();
// Affichage
return false;
}
}
Upvotes: 0
Views: 801
Reputation: 21
or you may use return FALSE; at the end of the function like this
$("#formCorrection{{ reponse.id }}").submit(function(event) {
$.ajax({
type: "POST",
url: "{{ path('paces_colle_correctioncolleqr_sauvegardercorrectionpassage') }}",
data: {note: note, commentaire: commentaire, idReponse: {{ reponse.id}}}
});
return false;
});
Upvotes: 2
Reputation: 8162
It's because submit button submit the form by default.
You can use event.preventDefault()
$("#formCorrection{{ reponse.id }}").submit(function(event) {
event.preventDefault();
event.stopPropagation();
$.ajax({
type: "POST",
url: "{{ path('paces_colle_correctioncolleqr_sauvegardercorrectionpassage') }}",
data: {note: note, commentaire: commentaire, idReponse: {{ reponse.id}}}
})
});
Upvotes: 1