Jhead45 of Covalence-Nashville
4/24/2018 - 9:49 PM

Sending input data to Server with JS

Inside the eventlistener the url is set to match the express.js path. Variables for the input boxes are pulled using .value. The URL is fetched and stringified.


document.getElementById('theForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var url = '/formsubmissions';

    var name = document.getElementById('input1').value;
    var email = document.getElementById('input2').value;
    var inputs = {
        name: `${name}`,
        email: `${email}`
    };
    
    fetch(url, {
        method: 'POST',
        body: JSON.stringify(inputs),
        headers: new Headers({
          'Content-Type': 'application/json'
        })
    }).then((res) => {
        console.log(res.status);
    }).catch((err) => {
        console.log(err);
    });
});