# Struggling with AJAX request for a form

**URL:** <https://forum.getkirby.com/t/struggling-with-ajax-request-for-a-form/31127>\
**Category:** Questions\
**Created:** [March 18, 2024, 1:20pm UTC](https://forum.getkirby.com/t/struggling-with-ajax-request-for-a-form/31127 "2024-03-18T13:20:31Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![konst](https://avatars.discourse-cdn.com/v4/letter/k/eada6e/32.png) [@konst](https://forum.getkirby.com/u/konst)\
**Post date:** [March 18, 2024, 1:20pm UTC](https://forum.getkirby.com/t/struggling-with-ajax-request-for-a-form/31127/1 "2024-03-18T13:20:31Z")

</div>

I am reopening a discussion from: [https://forum.getkirby.com/t/contact-form-controller-with-i18n-template/](https://forum.getkirby.com/t/contact-form-controller-with-i18n-template/)

I can’t get my head around calling an AJAX-request to prevent page refresh in a form.  
I have read through the forum and here and there are examples given but none fits my situation I think.

I started of without AJAX like this:

1. I have a snippet which contains a contact form. This snippet I use on various pages of a multilingual website.
2. Because I use this snippet on various pages, I use the site.php controller for handling the submit-data

This worked so far and now I wanted to implement an ajax-request to stop the page refresh.

The new snippet contains a script at the end like the following but I don’t know what url I have to pass.

Do I have to pass site.php? But how? Do I need routes?  
Or can I use an individual controller for my snippet? But how would I call it?

My rough Snippet

```auto
<form method="post">
<!-- -->
</form>
<script>
        let contactForm = document.querySelector('form');

        const handleForm = async (e) => {
            var formData = {
                name: $("#name").val(),
                email: $("#email").val(),
                text: $("#text").val(),
            };
            e.preventDefault();
            $.ajax({
                    type: "POST",
                    url: ???,
                    data: formData,
                    dataType: "json",
                    encode: true,
                })
                .done(function(data) {
 
// ... //

                    )
                .fail(function(data) {

// ... //
                });
        }
        contactForm.addEventListener('submit', handleForm);
        </script>

```

My site.php Controller:

```auto
<?php
// Controller for mail form
return function($kirby, $pages, $page) {

    $alert = null;

    if($kirby->request()->is('POST') && get('submit')) {

// ... //

    }

    return [
        'alert' => $alert,
        'data' => $data ?? false,
        'success' => $success ?? false
    ];
};

```

Thank you for all the help.

---

<div class="post-metadata">

**Author:** ![konst](https://avatars.discourse-cdn.com/v4/letter/k/eada6e/32.png) [@konst](https://forum.getkirby.com/u/konst)\
**Post date:** [March 18, 2024, 10:40pm UTC](https://forum.getkirby.com/t/struggling-with-ajax-request-for-a-form/31127/2 "2024-03-18T22:40:34Z")

</div>

Ok. I am on my way however I still have problems.  
if($kirby-\>request()-\>is(‘POST’)) is not true. Why is that?

Only if i wrap everything in _return function($kirby, $pages, $page) { }_. But this gives me new errors.

My script in my template

```auto

<form>
<!-- -->
</form>

<script>
        let contactForm = document.querySelector('form');

        const handleForm = async (e) => {
            e.preventDefault();
            var formData = {
                website: $("#website").val(),
                name: $("#name").val(),
                email: $("#email").val(),
                text: $("#text").val(),
            };

            $.ajax({
                type: "POST",
                url: "sendmymail",
                data: formData,
                dataType: 'json',

            }).done(function(response) {
                if (response.success) {
                    console.log(response.success);
                    
                } else if (response.alert) {
                    console.log(response.alert);
                }

            }).fail(function(xhr, textStatus, error) {
                
                console.error(error);
            });
        }
        contactForm.addEventListener('submit', handleForm);
        </script>

```

My template for the ajax-call - templates/sendmymail.php

```auto
<?php

    $alert = null;

    if($kirby->request()->is('POST')) {

// form logic //

      $success = 'The message has been sent.';
        
    }

echo json_encode([
    'alert' => $alert,
    'data' => $data ?? false,
    'success' => $success ?? false
]);

```

---

<div class="post-metadata">

**Author:** ![konst](https://avatars.discourse-cdn.com/v4/letter/k/eada6e/32.png) [@konst](https://forum.getkirby.com/u/konst)\
**Post date:** [March 18, 2024, 11:18pm UTC](https://forum.getkirby.com/t/struggling-with-ajax-request-for-a-form/31127/3 "2024-03-18T23:18:03Z")

</div>

Putting dump($\_POST); at the beginning of my template sendmymail.php results in nothing

I am really lost…

---

<div class="post-metadata">

**Author:** ![texnixe](https://dub1.discourse-cdn.com/flex017/user_avatar/forum.getkirby.com/texnixe/32/5754_2.png) [@texnixe](https://forum.getkirby.com/u/texnixe)\
**Post date:** [March 18, 2024, 11:30pm UTC](https://forum.getkirby.com/t/struggling-with-ajax-request-for-a-form/31127/4 "2024-03-18T23:30:29Z")

</div>

> [@konst](#):
>
> ```auto
> $.ajax({
> type: "POST",
> url: "sendmymail",
> data: formData,
> dataType: 'json',
> 
> ```

Are you using jQuery? Your code looks like a somewhat weird mix of vanilla JS and jQuery code…

---

<div class="post-metadata">

**Author:** ![konst](https://avatars.discourse-cdn.com/v4/letter/k/eada6e/32.png) [@konst](https://forum.getkirby.com/u/konst)\
**Post date:** [March 19, 2024, 8:52am UTC](https://forum.getkirby.com/t/struggling-with-ajax-request-for-a-form/31127/5 "2024-03-19T08:52:48Z")

</div>

Actually I don’t exactly know. I have read so many posts here in the forum from 2015 till now and might have messed up some stuff.

To short it down. I just want to find an ajax solution to my form because of the page refresh issue. And as I use this as a snippet on various templates, I couldn’t go for the standard template/controller structure.

During my experiments I managed to get something to work with a route in the config.php but I didn’t want to put all the data logic in the config.php as it overloads the place in my opinion.

Thank you for any help.

---

<div class="post-metadata">

**Author:** ![GB\_DESIGN](https://dub1.discourse-cdn.com/flex017/user_avatar/forum.getkirby.com/gb_design/32/14956_2.png) [@GB\_DESIGN](https://forum.getkirby.com/u/GB_DESIGN)\
**Post date:** [March 19, 2024, 9:12am UTC](https://forum.getkirby.com/t/struggling-with-ajax-request-for-a-form/31127/6 "2024-03-19T09:12:44Z")

</div>

> [@konst](#):
>
> I just want to find an ajax solution to my form because of the page refresh issue.

I use a self-programmed captcha, the value of which would be renewed after every reload, which is not desirable. Google for “Quform - Responsive Ajax Contact Form”. I use it successfully in all my projects. However, it is a very extensive tool that requires training time and PHP knowledge.  
I’m also looking for a more compact tool, but couldn’t find anything convincing.

---

<div class="post-metadata">

**Author:** ![konst](https://avatars.discourse-cdn.com/v4/letter/k/eada6e/32.png) [@konst](https://forum.getkirby.com/u/konst)\
**Post date:** [March 19, 2024, 9:24am UTC](https://forum.getkirby.com/t/struggling-with-ajax-request-for-a-form/31127/7 "2024-03-19T09:24:34Z")

</div>

Thank you for mentioning this but I expect that the right hint will help me to solve it without learning a newtool. As @texnixe already mentioned, I think I have just confused some logic here.

---

<div class="post-metadata">

**Author:** ![texnixe](https://dub1.discourse-cdn.com/flex017/user_avatar/forum.getkirby.com/texnixe/32/5754_2.png) [@texnixe](https://forum.getkirby.com/u/texnixe)\
**Post date:** [March 19, 2024, 10:11am UTC](https://forum.getkirby.com/t/struggling-with-ajax-request-for-a-form/31127/8 "2024-03-19T10:11:00Z")

</div>

Stick with vanilla JS and use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) for your Ajax request (and remove all this other $-jquery stuff). If you don’t have the jQuery library loaded (and imo you shouldn’t), then jQuery code will not work.

This recipe has an example fetch request: [Load more with Ajax | Kirby CMS](https://getkirby.com/docs/cookbook/content-representations/ajax-load-more). Totally different example, though with only a GET request, so you need to modify this to post the data instead.
