0

I have seen examples for how to POST form data via FETCH but they seem to either add form variables 1 by 1, or send the whole thing via JSON.

For reference, I use JQUERY $.post without issues, but i wanted to start using FETCH.

My current code is:

$(".btn_submit").on("click",function (){
let postvars;
        postvars = $('#myForm').serializeArray();
        //postvars.push({name: 'newvar', value: 123}); //uncomment if you need to add vars in the postvars

        let url = "engine/api.php";
        let act = "";
        $.post(`${url}?act=${act}&=`, postvars, function (data) {
            var stat = data.stat;
            var statMsg = data.statMsg;
            var myData = data.data;

            if (stat == 'ok') {
                notify(statMsg, "success");


        }).fail(function (d) {
            showAlert(d.status)
        });
 });

This works perfectly for me.

But I can't seem to find an equivalent of that via FETCH. Best i could get at is:

            let form = document.getElementById("myForm");
            let formData = new FormData(form);
            let url = "engine/api.php";
            let act = "registration-details-clients";
            fetch(`${url}?act=${act}&=`, {method:'post', body: formData})
                .then(response => response.json())
                .then(data => {
                    var stat = data.stat;
                    var statMsg = data.statMsg;
                    var myData = data.data;

                    if (stat == 'ok') {
                        notify(statMsg, "success");

                    } else {
                        showAlert(statMsg, 'error');
                    }
                })
                .catch((error) => {
                    console.error('Error:', error);
                    showAlert(d.status);
                });
            // END:

        });

but checking debugger and this seems to send a weird payload (raw?)

   -----------------------------20933611634071352467338304530
  Content-Disposition: form-data; name="fname"
BrownChiLD
  • 3,545
  • 9
  • 43
  • 61
  • From the duplicate, see [this answer](https://stackoverflow.com/a/69941251/283366) – Phil May 18 '22 at 02:01
  • nope, that too requires me to declare each variable in the form either manually or in loop .. there has to be a better way like my current method using jquery! (serialize?) – BrownChiLD May 18 '22 at 03:16
  • No it doesn't. All you need is `let formData = new URLSearchParams(new FormData(form))`. That's the only change you'd need to make to your current code. I'm not sure how the answer I linked doesn't solve it for you – Phil May 18 '22 at 03:51

0 Answers0