簡體   English   中英

用AJAX發送的Symfony表單

[英]Symfony form sent with AJAX

我想用AJAX發送Symfony表單。 我已經做到了,但是在代碼中找不到錯誤。 當我單擊Submit時,它將發送表單,但不發送AJAX。

在控制器中創建表單

$form = $this->createForm(CorrectionReponseQRFormType::class, $passage)->createView();

樹枝

{{ 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;
    }
}

或者您可以使用return 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;
});

這是因為默認情況下,“提交”按鈕提交表單。

您可以使用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}}}
        })
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM