Home > Blockchain >  How to send selected Radio Button through JSON
How to send selected Radio Button through JSON

Time:03-17

I am creating a REST API and that will receive JSON data through POST. I'm creating the structure of the JSON now and was wondering what is considered best practice for how to send data signifying which Radio Button was selected on the sender's side. I thought of 3 possible ways to do it, but I'm open to other options if there's something better. Here are the 3 ways with UPS, FedEx and USPS being the sample options:

"UPS": false, "FedEx": true, "USPS": false

"ShippingCompany": 2 // 1 for UPS, 2 for FedEx, 3 for USPS

"ShippingCompany": "FedEx"

CodePudding user response:

It depends on the use case and on who's consuming the API.

Your first solution is the least favorable of these three, since you want to implement a radio button. This would be more of a checkbox situation.

Variant 2 and 3 are interchangeable, but I'd use 3, since it's obvious what company you mean, instead of having to look up the meaning of the integers.

To go even further you could take a look at enums and their definition in openapi.

CodePudding user response:

You can get it easily with querySelector:

let el = document.querySelector("input[name=radioName]:checked");
let val = el !== null ? el.value : "";

In your json you use like:

json = {
     radioName: val 
}

And then, to post, perhaps you may have to stringfy the json. Here is a sample code using the Fetch Api and recieves a json from the backend.

const getAllIncidents = () => { var reqHeaders = new Headers();

            var reqInit = { method: 'GET',   
               headers: reqHeaders,
               mode: 'cors',
               cache: 'default' ,
               body: JSON.stringify( { 
                    radioName: val 
                })
               };
            fetch(service_url, reqInit)
            .then( r => {
                return r.json();
            }).then( json => {
                console.log(json);
            });
        }

Obs 1.: querySelector returns null if the selector returns no element. Obs 2.: remember using the same name for the radio button collection and diferent id for each one.

  • Related