Making Request Using Fetch API

Fetch API is similiar to XMLHttpRequest but this new API provides powerful features.

Browser Compability of Fetch API

While it's powerful and flexible Internet Explorer still does not compability fetch api, so you may want to think twice to use it in production detailed browser support for Fetch API:

JSON Request Using Fetch API

Let's make a simple request

<script>
    fetch('https://formcarry.com/s/yourFormId', {
      method: 'POST',
      headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
      body: JSON.stringify({name: 'Alex', surname: 'Moran'})
    })
    .then(response => console.log(response))
    .catch(error => console.log(error))
</script>

Output:

{ok: true, redirected: false, status: 200}

To try it, just change the url to your forms url.

x-www-form-url-encoded Request Using Fetch API

Let's make a simple request

<script>
    fetch('https://formcarry.com/s/yourFormId', {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-url-encoded', 'Accept': 'application/json'},
      body: 'name=alex&surname=moran'
    })
    .then(response => console.log(response))
    .catch(error => console.log(error))
</script>

Output:

{ok: true, redirected: false, status: 200}

There's a function for you to turn your javascript object to valid format

let formData = {name: 'Alex', surname: 'Moran'};

// function
const encodeFormData = (data) => {
    return Object.keys(data)
        .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
        .join('&');
}

// usage
encodeFormData(formData);

// output
// name=Alex&surname=Moran

// using in fetch
fetch('https://formcarry.com/s/yourFormId', {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-url-encoded', 'Accept': 'application/json'},
    body: encodeFormData(formData)
})
.then(response => console.log(response))
.catch(error => console.log(error))