У меня есть форма, которую я отправляю в POST в AJAX, и если эта форма действительна, я возвращаю новую форму, которую я хочу отправить автоматически в Jquery.Я чувствую, что мой .submit () полностью игнорируется, я не понимаю ..
Я пытался сделать console.log () до и после вызова функции submit (), они хорошо отображаются, этоочень странно ..
Мой основной вид (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'