jQuery函数Submit()在Ajax成功函数中不起作用

时间:2019-02-09 13:55:55

标签: javascript jquery ajax symfony twig

我有一个表单,该表单是在AJAX中的POST中提交的,如果此表单有效,我将返回一个新表单,该表单要在Jquery中自动提交。我觉得我的.submit()完全被忽略了,我不明白。

我试图在调用commit()函数之前和之后制作console.log(),它们显示的很好,这很奇怪。

我的主视图(show.html.twig):

{% block body %} 
            <div class="text-center">
                <img src="{{ asset('loader/loader.gif', 'image_site') }}" alt="Loader Just Pronos" id="spinner" class="mt-30">
            </div>

            <div id="userForm">
                {{ form_start(form, {'attr': {'class': 'contact-form user-form'}}) }}

                <div class="row mt-10" id="formError">
                    <div class="col-12">
                        {{ form_errors(form) }}
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <div class="name-input">
                            {{ form_widget(form.nom) }}
                            {{ form_errors(form.nom) }}
                        </div>
                    </div>

                    <div class="col">
                        <div class="name-input">
                            {{ form_widget(form.prenom) }}
                            {{ form_errors(form.prenom) }}
                        </div>
                    </div>

                    <div class="col">
                        <div class="box-input">
                            {{ form_widget(form.pays) }}
                            {{ form_errors(form.pays) }}
                        </div>
                    </div>
                </div>

                <div class="row mt-10">
                    <div class="col">
                        <div class="box-input">
                            {{ form_widget(form.tel) }}
                            {{ form_errors(form.tel) }}
                        </div>
                    </div>

                    <div class="col">
                        <div class="email-input">
                            {{ form_widget(form.email) }}
                            {{ form_errors(form.email) }}
                        </div>
                    </div>
                </div>

                <div class="row mt-10">
                    <div class="col">
                        <p class="mt-15"><em>* Après avoir soumis ce formulaire, vous serez automatiquement redirigé sur la plateforme de paiement sécurisée Klik&Pay.</em></p>
                        <div class="input-submit">
                            {{ form_widget(form.submit) }}
                        </div>
                    </div>
                </div>

                {{ form_end(form) }}
            </div>
        </div>
    </section>
{% endblock %}
{% block js %}
    <script>
        $(function () {
            let registerForm = "{{ path('site_devenir_vip_ajax_payment_form') }}";

            $("#spinner")
                .hide();

            $(document)
                .on("submit", "form", function (e) {
                    e.preventDefault();

                    $.ajax({
                        url: registerForm,
                        type: "POST",
                        dataType: "json",
                        data: $(this)
                            .serialize(),
                        beforeSend: function () {
                            $("#spinner")
                                .show();
                        },
                        success: function (data, textStatus, xhr) {
                            if (xhr.status === 200 && textStatus === 'success') 
                            {
                                $("#userForm")
                                    .html(data.template);
                                console.log("here 1");
                                $("#paymentForm").submit();
                                console.log("here 2");
                            } else {
                                console.log(data);
                            }
                        },
                        complete: function () {
                            $("#spinner")
                                .hide();
                        },
                        error: function (jqXHR, status, error) {

                        },
                    });
                });
        });
    </script>
{% endblock %}

第二种形式(klik_and_pay_form.html.twig):

{% form_theme formKlikAndPay 'site/form_theme/form_div_layout.html.twig' %}

{{ form_start(formKlikAndPay, {'attr': {'class': 'contact-form user-form', 'action': 'https://www.klikandpay.com/paiementtest/checkabon.pl', 'id': 'paymentForm', 'method': 'POST'}}) }}

<div class="row mt-10" id="formError">
    <div class="col-12">
        {{ form_errors(formKlikAndPay) }}
    </div>
</div>

<div class="row">
    <div class="col">
        <div class="name-input">
            {{ form_widget(formKlikAndPay.nom) }}
            {{ form_errors(formKlikAndPay.nom) }}
        </div>
    </div>

    <div class="col">
        <div class="name-input">
            {{ form_widget(formKlikAndPay.prenom) }}
            {{ form_errors(formKlikAndPay.prenom) }}
        </div>
    </div>

    <div class="col">
        <div class="box-input">
            {{ form_widget(formKlikAndPay.pays) }}
            {{ form_errors(formKlikAndPay.pays) }}
        </div>
    </div>
</div>

<div class="row mt-10">
    <div class="col">
        <div class="box-input">
            {{ form_widget(formKlikAndPay.tel) }}
            {{ form_errors(formKlikAndPay.tel) }}
        </div>
    </div>

    <div class="col">
        <div class="email-input">
            {{ form_widget(formKlikAndPay.email) }}
            {{ form_errors(formKlikAndPay.email) }}
        </div>
    </div>
</div>

{{ form_row(formKlikAndPay.accountId) }}
{{ form_row(formKlikAndPay.abonnementId) }}

<div class="row mt-10">
    <div class="col">
        <p class="mt-15"><em>* Après avoir soumis ce formulaire, vous serez automatiquement redirigé sur la plateforme de paiement sécurisée Klik&Pay.</em></p>
        <div class="input-submit">
            {{ form_widget(formKlikAndPay.submit) }}
        </div>
    </div>
</div>

{{ form_end(formKlikAndPay) }}

控制器:

/**
     * @Route("/{id<\d+>?1}/{slug}", methods={"GET", "POST"}, name="show")
     * @Security("is_granted('IS_AUTHENTICATED_ANONYMOUSLY')")
     */
    public function show(Request $request, Offre $offre, $slug): Response
    {
        if ($offre->getSlug() !== $slug) {
            return $this->redirectToRoute('site_devenir_vip_show', [
                'id'   => $offre->getId(),
                'slug' => $offre->getSlug(),
            ], Response::HTTP_MOVED_PERMANENTLY);
        }

        $utilisateur = new User();

        $form = $this->createForm(UserPaiementType::class, $utilisateur);
        $form->handleRequest($request);

        $session = new Session(new NativeSessionStorage(), new AttributeBag());
        $session->set('offre', $offre->getId());

        return $this->render('site/pages/devenir_vip/show.html.twig', [
            'form'  => $form->createView(),
            'offre' => $offre,
        ]);
    }

    /**
     * @Route("/load-payment-form", name="ajax_payment_form", condition="request.isXmlHttpRequest()", methods={"GET", "POST"})
     */
    public function ajaxKlikAndPayForm(Request $request): Response
    {
        $utilisateur = new User();

        $form = $this->createForm(UserPaiementType::class, $utilisateur);
        $form->handleRequest($request);

        if ($form->isSubmitted() === true) {
            if ($form->isValid() === true) {
                if ($request->getSession() === null) {
                    return new Response('Une erreur s\'est produite pendant la récupération de l\'offre.');
                }

                $offreSession = $request->getSession()->get('offre');
                $offre        = $this->entityManager->getRepository(Offre::class)->find($offreSession);

                $klikAndPayPaiement = new KlikAndPayPaiement();
                $klikAndPayPaiement->setPrenom($utilisateur->getPrenom());
                $klikAndPayPaiement->setNom($utilisateur->getNom());
                $klikAndPayPaiement->setPays($utilisateur->getPays());
                $klikAndPayPaiement->setEmail($utilisateur->getEmail());
                $klikAndPayPaiement->setTel($utilisateur->getTel());
                $klikAndPayPaiement->setAccountId($this->getParameter('app.klik_and_pay.account_id'));
                $klikAndPayPaiement->setAbonnementId($offre->getIdKlik());

                $formKlikAndPay = $this->createForm(KlikAndPayPaiementType::class, $klikAndPayPaiement);
                $formKlikAndPay->handleRequest($request);

                $response = [
                    'template' => $this->renderView('site/layout/partials/ajax/klik_and_pay_form.html.twig', [
                        'formKlikAndPay' => $formKlikAndPay->createView(),
                    ]),
                ];

                return new JsonResponse($response, JsonResponse::HTTP_OK);
            }

            return new Response('Le formulaire comporte des erreurs.');
        }

        $offreSession = $request->getSession()->get('offre');
        $offre        = $this->entityManager->getRepository(Offre::class)->find($offreSession);

        $klikAndPayPaiement = new KlikAndPayPaiement();
        $klikAndPayPaiement->setPrenom($utilisateur->getPrenom());
        $klikAndPayPaiement->setNom($utilisateur->getNom());
        $klikAndPayPaiement->setPays($utilisateur->getPays());
        $klikAndPayPaiement->setEmail($utilisateur->getEmail());
        $klikAndPayPaiement->setTel($utilisateur->getTel());
        $klikAndPayPaiement->setAccountId($this->getParameter('app.klik_and_pay.account_id'));
        $klikAndPayPaiement->setAbonnementId($offre->getIdKlik());

        $formKlikAndPay = $this->createForm(KlikAndPayPaiementType::class, $klikAndPayPaiement);
        $formKlikAndPay->handleRequest($request);

        return $this->render('site/layout/partials/ajax/klik_and_pay_form.html.twig', [
            'formKlikAndPay' => $formKlikAndPay->createView(),
        ]);
    }

您知道为什么jquery函数Submit()无法正常工作吗?

更新:

我尝试过这个:

$("#paymentForm").trigger("submit");
$("#paymentForm")[0].trigger("submit");
$("#paymentForm").submit();
$("#paymentForm")[0].submit();

let submitPayment = $('button[name="submit"]');
$(submitPayment).trigger('click');

然后我在form_start中添加了它:

'method': 'POST'

3 个答案:

答案 0 :(得分:1)

您已阻止jQuery提交处理程序中的默认设置

您可以通过以下方式使用本机提交:

$("#paymentForm").submit();

收件人

$("#paymentForm")[0].submit();

jQuery提交监听器将不会监听本地提交事件

答案 1 :(得分:0)

确定尝试使用这种东西:

let submitPayment = $('button[name="klik_and_paypaiement_form[submit]"]'); //see in the html the good name of your button
$(submitPayment).trigger('click');

答案 2 :(得分:0)

我在我的项目中尝试过,效果很好:

function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );

})