'How to send form data to API post via JavaScript

I have a form in my project and when it is submitted I need to send the data to an API and receive the response to check if there's an errors

the html

<form id="contactForm" class="w-75 mx-auto">
    <input type="text" class="form-control bg-transparent" placeholder="Name">
    <input type="email" class="form-control bg-transparent my-3" placeholder="E-mail">
    <textarea class="form-control bg-transparent" placeholder="Your Message"></textarea>
    <button type="submit" class="my-3 px-4 py-2 rounded-3">SEND</button>
</form>

the js

$('#contactForm').submit(function (e) {
    e.preventDefault();

});


Solution 1:[1]

This should work. Make sure URL for API and web should be the same else you could get cross site error:

<form id="contactForm" class="w-75 mx-auto" action="http://yourAPI.com">
    <input type="text" class="form-control bg-transparent" placeholder="Name">
    <input type="email" class="form-control bg-transparent my-3" placeholder="E-mail">
    <textarea class="form-control bg-transparent" placeholder="Your Message"></textarea>
    <button type="submit" class="my-3 px-4 py-2 rounded-3">SEND</button>
</form>

<script
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous"></script>

<script>
    $('#contactForm').submit(function (e) {
        e.preventDefault(); // avoid to execute the actual submit of the form.

        
        var form = $(this);
        var url = form.attr('action');
        
        $.ajax({
            type: "POST",
            url: url,
            data: form.serialize(), // serializes the form's elements.
            success: function(data)
            {
                alert(data); // show server response 
            }
        });
    });
</script>

Solution 2:[2]

You can use fetch api and the POST method to send data to an api. Since you have not provided how your api works or how the data is to be passed I cannot provide further help, but i can guide you to the correct path.

Read more about fetch api in javascript

(async function () {
    const url = ''; // your api endpoint here
    const res = await fetch(url, { method: 'POST' });
    // res corresponds to the api response;
})();

Since you're using jQuery, you should probably read jQuery post method

Solution 3:[3]

$("#contactForm").submit( async (e) => {
    e.preventDefault();
    const data = {
        name: e.target.elements[0].value,
        email: e.target.elements[1].value,
        message: e.target.elements[2].value,
    }
    const response = await fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when- 
       downgrade, origin, origin-when-cross-origin, same-origin, strict- 
       origin, strict-origin-when-cross-origin, unsafe-url
       body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
})

Solution 4:[4]

let formData = new FormData();
formData.append('variable1', variable1);
formData.append('variable2', variable2);

url = `url`
options = {
  method: 'POST',
  body: formData
}

let response = await request(url, options)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Twister
Solution 2
Solution 3
Solution 4 Tyler2P