Video

Latest

How to send data using FormData and Fetch API




1. Create Form in a html
2. Create a JS for that form that will send the value of the form to backend
3. Create a PHP for getting data from DB and getting response as JSON (for GET request)
4. Create frontend on the same html , parse JSON and map accordingly



1. Create Form in a html


<form class="form-horizontal" id="sendMessageForm">
    <div class="form-group mb-5" style="float:bottom;">
        <div class="d-flex justify-content-center">
            <div class="px-3">
                <textarea name="msg" class="form-control" style="min-width:30rem;" placeholder="Write Your Messeage Here!"></textarea>
            </div>
            <button type="submit" class="btn btn-primary px-4" id="sendButton">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-send-fill" viewBox="0 0 16 16">
                    <path fill-rule="evenodd" d="M15.964.686a.5.5 0 0 0-.65-.65L.767 5.855H.766l-.452.18a.5.5 0 0 0-.082.887l.41.26.001.002 4.995 3.178 3.178 4.995.002.002.26.41a.5.5 0 0 0 .886-.083l6-15Zm-1.833 1.89.471-1.178-1.178.471L5.93 9.363l.338.215a.5.5 0 0 1 .154.154l.215.338 7.494-7.494Z"/>
                </svg>
            </button>
        </div>
    </div>
</form>

2. Create a JS for that form that will send the value of the form to backend


function onSend(e) {
    // console.log('onSend Works!');
    e.preventDefault();
    const formData = new FormData(document.forms.sendMessageForm);
    // log formData
    for (var pair of formData.entries()) {
        console.log(pair[0]+ ': ' + pair[1]);
    }
}

let sendButton = document.getElementById('sendButton');
sendButton.addEventListener('click', onSend);


(3 and 4 will be uploaded soon)

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".

So when using FormData you are locking yourself into multipart/form-data. There is no way to send a FormData object as the body and not sending data in the multipart/form-data format.

If you want to send the data as application/x-www-form-urlencoded you will either have to specify the body as an URL-encoded string, or pass a URLSearchParams object. The latter unfortunately cannot be directly initialized from a form element. If you don’t want to iterate through your form elements yourself (which you could do using HTMLFormElement.elements), you could also create a URLSearchParams object from a FormData object:

const data = new URLSearchParams();
for (const pair of new FormData(formElement)) {
    data.append(pair[0], pair[1]);
}

fetch(url, {
    method: 'post',
    body: data,
})
.then(…);

Note that you do not need to specify a Content-Type header yourself.


As noted by monk-time in the comments, you can also create URLSearchParams and pass the FormData object directly, instead of appending the values in a loop:

const data = new URLSearchParams(new FormData(formElement));

This still has some experimental support in browsers though, so make sure to test this properly before you use it.

No comments