cancel
Showing results for 
Search instead for 
Did you mean: 

Submit a custom form with Fetch API

SOLVED

Submit a custom form with Fetch API

Hi,

 

I’m trying to submit my custom form with Fetch API (not $.ajax), and for some reason it’s not working. If I’m submitting the same form with $.ajax the data is sent and a success callback is triggered, but when I’m trying to do the same with native Fetch API I’m getting an error and the data isn’t sent.

 

Here’s jQuery code:

let status = document.getElementById("my-form-status");
jQuery('body').on('click', '#contactus-form .btn.btn-default', function(e){
    e.preventDefault();
    e.stopImmediatePropagation();
    jQuery.ajax({
        type: 'post',
        url: '/customcontact/index/submit',
        data: jQuery('#contactus-form').serialize(),
        cache: false,
        showLoader: 'true',
        success: function(response) {
            console.log(response.success);
            status.innerHTML = "Thanks for your submission!";
        }
    });
    return false;
});

 

Fetch request:

const form = document.querySelector("#contactus-form");

form.addEventListener("submit", (event) => {
    event.preventDefault();
    const body = new FormData(form);
    const response = fetch('/customcontact/index/submit', {
            method: 'POST',
            body
        })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(err => console.log(err));
});

When I’m submitting it with Fetch API I’m getting this error:

`SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON`

 

The response in my controller is:

$jsonResponse = $this->resultFactory->create(ResultFactory::TYPE_JSON);
$jsonResponse->setData([
    'name' => 'name'
]);
return $jsonResponse;
1 ACCEPTED SOLUTION

Accepted Solutions

Re: Submit a custom form with Fetch API

Figured it out. The problem is `form_key` isn’t added to the FormData.

Appending it solves the issue:

body.append('form_key', document.querySelector('input[name="form_key"]').value);

 

View solution in original post

1 REPLY 1

Re: Submit a custom form with Fetch API

Figured it out. The problem is `form_key` isn’t added to the FormData.

Appending it solves the issue:

body.append('form_key', document.querySelector('input[name="form_key"]').value);