简体   繁体   中英

How to use Fetch API to retrieve and send data from form?

I have html form:

<form action="file.php" method="post">
    <input name="formName" type="text" />
    <input name="formEmail" type="email" />
    <input name="formSubmit" type="submit" value="Submit Me!" />
</form>

So how to use Fetch API in order to get those values and send them to file.php file using ajax?

Using Fetch API

 function submitForm(e, form){ e.preventDefault(); fetch('file.php', { method: 'post', body: JSON.stringify({name: form.formName.value, email: form.formEmail.value}) }).then(function(response) { return response.json(); }).then(function(data) { //Success code goes here alert('form submited') }).catch(function(err) { //Failure alert('Error') }); } 
 <form action="file.php" method="post" onsubmit="submitForm(event, this)"> <input name="formName" type="text" /> <input name="formEmail" type="email" /> <input name="formSubmit" type="submit" value="Submit Me!" /> </form> 

I would recommend to use FormData . It uses the same format a form would use if the encoding type were set to "multipart/form-data". More details about it.

    const submitForm = () => {
        const formEl = document.getElementById('formId');
        const payload = new FormData(formEl);

        fetch('file.php', {
            method: 'POST',
            body: payload,
        })
        .then(Result => Result.json())
        .then(data => {
            console.log(data);
            // your code comes here
        })
        .catch(errorMsg => {
            console.log(errorMsg);
        });

    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM