我想用AJAX发送Symfony表单。我已经做到了,但我无法在代码中找到错误。当我点击提交时,它发送表单但不是AJAX。
在控制器中创建表单:
$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>
控制器功能:
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;
}
}
答案 0 :(得分:2)
或者您可以使用返回FALSE;在这个函数的最后
$("#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;
});
答案 1 :(得分:1)
这是因为提交按钮默认提交表单。
您可以使用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}}}
})
});