How to handle form request form in modal window with AJAX request

Hi,
I have a page with a modal window, that contains a contact form
I want to find the way how to process AJAX request from this form

Thanks,
Pavlo

see this thread: https://discourse.getgrav.org/t/path-to-ajax-request/6654/3

1 Like

@Pavlo,

For the <form>, I use $this->grav[‘page’]->slug() for the action attribute and add a hidden field with a name unique to my contactform.

On submit of the form I check if the name of the hidden field isset in $_POST.

The reason I don’t use an arbitrary value for the action attribute is that if Javascript is not handling the form for some reason and the page is not submitted through Ajax, a 404 error will be thrown.

Note: I’m not using Grav’s forms, but custom bootstrap v4+ forms.

Twig:

<form action="{{ contactForm.action }}" method="post" id="contactform">
    <fieldset>
        <input type="hidden" name="{{ contactForm.name }}">
[...]

PHP:

if (isset($_POST[self::FORMNAME]) {
   $this->result = $this->handleForm();

   if ($this->isAjaxRequest()) {
      echo json_encode($this->result);
      die();
   }
}
// continue page creation if not Ajax request
1 Like