Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Forms & Blueprints

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

form

Solved by pamtbaau View solution

Started by Pavlo 8 years ago · 2 replies · 1130 views
8 years ago

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

8 years ago Solution

@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:

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

PHP:

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
last edited 06/23/18 by pamtbaau

Suggested topics

Topic Participants Replies Views Activity
Forms & Blueprints · by Ton Haarmans, 5 years ago
13 1139 4 months ago
Forms & Blueprints · by Hugo Oliveira, 5 months ago
0 63 5 months ago
Forms & Blueprints · by Flachy Joe, 6 months ago
9 137 6 months ago
Forms & Blueprints · by Augustus, 7 months ago
7 112 7 months ago
Forms & Blueprints · by Julien, 7 months ago
10 131 7 months ago