Confusion with fetch()

Im submitting this form using fetch and am confused in displaying the data

 <form id="add_poc_form" onsubmit="return fetchpost()">
...
    <script>
    function fetchpost () {
      // (A) GET FORM DATA
      var form = document.getElementById("add_poc_form");
      var data = new FormData(form);

      // (B) FETCH
      fetch("add_poc_engine.php", {
        method: "post",
        body: data
      })
      .then((res) => { return res.text(); })
      .then((txt) => { console.log(txt); })
      .catch((err) => { console.log(err); });

      // (C) PREVENT HTML FORM SUBMIT
      return false;
    }
    </script>

the result,


then, if I refresh

so its working, but can I get the table to refresh when the function runs?

Here’s how I create and display a High Score Table using Fetch, the key is to use JSON.stringify or making sure the data is in JSON format to begin with when sending the data in the proper format:

    /* Handle General Errors in Fetch */
    const handleErrors = function (response) {
        if (!response.ok) {
            throw (response.status + ' : ' + response.statusText);
        }
        return response.json();
    };
    /*
     * Create and Display High Score Table
     */
    const displayHSTable = (info) => {
        highScoresDisplay.style.display = "block";
        info.forEach((value, index) => {
            let anchor = d.querySelector('.anchor');
            let trElement = anchor.appendChild(d.createElement('tr'));
            if ((index + 1) % 2 === 0) {
                trElement.className = 'active-row';
            }
            let tdPlayer = trElement.appendChild(d.createElement('td'));
            let tdPoints = trElement.appendChild(d.createElement('td'));
            tdPlayer.appendChild(d.createTextNode(value.player));
            tdPoints.appendChild(d.createTextNode(value.score));
        });
    }

    /* Save User Data to hs_table */
    const saveHSTableSuccess = (info) => {

        if (info) {
            removeHighScores();
            createHSTable('retrieveHighScore.php', retrieveHSTableUISuccess, retrieveHSTableUIError);
        }

    };

    /* If Database Table fails to save data in mysql table */
    const saveHSTableUIError = function (error) {
        console.log("Database Table did not load", error);
    };


    /* create FETCH request */
    const saveHSTableRequest = (saveUrl, succeed, fail) => {
        fetch(saveUrl, {
            method: 'POST', // or 'PUT'
            body: JSON.stringify(hs_table)
        })
            .then((response) => handleErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
    };

    /* retrieve User Data from hs_table */
    const retrieveHSTableUISuccess = function (info) {
        displayHSTable(info);

    };

    /* If Database Table fails to save data in mysql table */
    const retrieveHSTableUIError = function (error) {
        console.log("Database Table did not load", error);
    };

    /* Create High Score Data using fetch */
    const createHSTable = (retrieveUrl, succeed, fail) => {

        let max = 5; // Maximum Records to Be Displayed
        let maximum = {};
        maximum.max_limit = max;

        fetch(retrieveUrl, {
            method: 'POST', // or 'PUT'
            body: JSON.stringify(maximum)
        })
            .then((response) => handleErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
    };

    createHSTable('retrieveHighScore.php', retrieveHSTableUISuccess, retrieveHSTableUIError);

Here’s another example of a contact form that I did

    /* Success function utilizing FETCH */
    const sendUISuccess = function (result) {
        //console.log('Result', result);
        if (result) {
            d.querySelector('#recaptcha').style.display = "none";
            submit.style.display = "none";
            d.querySelector('.pen').setAttribute('src', 'assets/images/target.png');
            //messageSuccess.style.display = "block";
            d.querySelectorAll('form > *').forEach(function (a) {
                a.disabled = true;
            });
        }
    };

    /* If Database Table fails to update data in mysql table */
    const sendUIError = function (error) {
        console.log("Database Table did not load", error);
    };

    const handleSaveErrors = function (response) {
        if (!response.ok) {
            throw (response.status + ' : ' + response.statusText);
        }
        return response.json();
    };


    const saveRequest = (sendUrl, succeed, fail) => {

        fetch(sendUrl, {
            method: 'POST', // or 'PUT'
            body: JSON.stringify(sendEmail)

        })
            .then((response) => handleSaveErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
    };

    submit.addEventListener('click', (e) => {

        e.preventDefault();

        sendEmail.phone = phone.value;
        sendEmail.website = website.value;
        sendEmail.response = submit.getAttribute('data-response');
        if (email.value === '') {
            email.placeholder = "Email Address is Invalid!";
            email.style.borderColor = "red";
            email.focus();
        }
        if (sendStatus.name && sendStatus.email && sendStatus.comments) {
            submit.style.display = "none";
            notice.style.display = "grid";

            d.querySelector('.pen').setAttribute('src', 'assets/images/hour-glass.png');
            message.style.display = "flex";
            saveRequest(sendUrl, sendUISuccess, sendUIError);
        } else {
            notice.style.display = "block";
            notice.textContent = "Name, Email, and Message Required!";
        }
    }, false);


};

I think I comment it out pretty good and hope it helps?

John

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.