How to send selected Radio Button through JSON - json

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"

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.

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

accessing deep nested API JSON objects (React JS) [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I am attempting to create a weather app using the Openweather API. I am able to retrieve the JSON object successfully, but I am having trouble iterating through the object, I would like to access the weather details for specific dates and times but I just cannot for the life of me wrap my head around the concept. There were times where I was able to access the name of the JSON object, but when I attempt to access a specific weather detail from a specific date and time, I am met with errors constantly. Some of the information is so deeply nested that I am unsure exactly how to retrieve the information
fetch(`https://api.openweathermap.org/data/2.5/forecast?zip=${zip}&units=imperial&appid=5672e526c1cbc8d71aed230e5e151426`)
.then(response => response.json())
.then(json => {
console.log(json.list);
});
}, [apiSearch]);
If I simply try to add an index to the end of json.list:
console.log(json.list[1]);
I am sometimes met with errors such as Cannot convert undefined or null to object or something along those lines, I would like to know the best way to access the object array below and all of its information, thank you!
I've tried multiple approaches including Object.keys, mapping, etc. but I always get hit with an object is null error or something of the sorts. I would like to iterate through the 40 arrays and lets say access the temperature, every attempt to do so has led me to failure. Any help would be greatly appreciated, thank you!
Hope this will help you.
fetch(`https://api.openweathermap.org/data/2.5/forecast?zip=99501&units=imperial&appid=5672e526c1cbc8d71aed230e5e151426`)
.then(response => response.json())
.then(json => {
const forcasetList = json.list;
forcasetList.forEach(f => {
console.log(f.main.temp)
})
});
There can be several issues here:
Fetch and response status
Since you are using fetch the returned response may not always be a valid response, you should first check that you have an HTTP 200 status response e.g.:
fetch(url).then(
response => {
if (response.status !== 200) {
throw new Error(`Expected status 200 ok got status: ${response.status}`)
}
return response.json()
}
).then(...)
Impartial / Invalid data
I am not familiar with the openweathermap API but from what i can see in the API the forecast list should always have complete non null objects.
But you could add some validation or guards by either e.g.:
Using a JSON schema validation like AVJ
Or having a parse method that checks for the list and returns non null elements
fetch(url).then(
response => {
if (response.status !== 200) {
throw new Error(`Expected status 200 ok got status: ${response.status}`)
}
return response.json()
}
).then(
forecast => {
// here you could validate using something like AVJ to
// check that the json response is valid
if (!valid(forecast)) {
throw new Error('Invalid forecast data')
}
// Some custom filtering and validation example
const list = forecast.list || []
return list.filter(
item => {
// filter out null objects
if (!item) {
return false
}
// other validations.
...
// validate the date is within your range
if (item.dt ...) {
return false
}
// valid item
return true
}
)
.map (
// extract the weather part
item => item.weather
)
}
).then(
weatherItems => {
// work with weather items here
}
)

What Parameter Contact Form 7 using JSON to sent using API

I want create API for contact form 7.
How to send data from front-end to Contact Form 7 using WP rest api?
I mean, what should the data structure be to send it via the POST method?
http://xx.xxx/wp-json/contact-form-7/v1/contact-forms/<id-form>/feedback
I trying different ways, but request always return response “validation_failed”, “One or more fields contain erroneous data. Please check them and try again.”
I did not find anything about this in the documentation.
Were you able to find the solution? I've been working with the Contact Form 7 REST API and there are a few things you need to do to be abled to get a 'success' response, instead of validation_failed.
First, you need to know what form fields you need to submit. This is set up in your CF7's contact form. The field's name is defined in contact form. Most likely, CF7 uses the naming structure your-name and your-email. So you will need to format your post body to match this.
Next, you will need to submit it using FormData() https://developer.mozilla.org/en-US/docs/Web/API/FormData. From personal experience, I found that if I send my request as a normal object by using post, CF7 sends back validation_failed.
Note: I am using Nuxt's http package to submit data, but you are able to use axios here.
// Format your body response
const emailBody = {
"your-name": this.form.name,
"your-email": this.form.email,
"your-message": this.form.message,
};
// Create a FormData object, and append each field to the object
const form = new FormData();
for (const field in emailBody) {
form.append(field, emailBody[field]);
}
// Submit your form body using axios, or any other way you would like
const response = await this.$http.post(this.getEndEndpoint, form);
This is working for me, I am no longer getting the status validation_failed. Instead I now get a spam status. Trying to solve this problem now
Good luck
add_filter( 'wpcf7_mail_components', 'show_cf7_request', 10, 3 );
function show_cf7_request( $components, $wpcf7_get_current_contact_form, $instance ) {
print_r($_REQUEST);
die();
return $components;
};
Don't try on LIVE ;)
// google recaptcha integration v3 with contact form 7 Rest API
let email = $('input.email').val();
let g_recaptcha_response = $('textarea.g-recaptcha-response').val();
let data = new FormData(form);
data.append("email", email);
data.append("_wpcf7_recaptcha_response", g_recaptcha_response);
// _wpcf7_recaptcha_response key is important and should be same
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/wp-json/contact-form-7/v1/contact-forms/783/feedback",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
}).then((data) => {alert(data.message);});

Should I convert JSON to Array to be able to iterate it with v-for?

In the following code I am getting data from server and filling array with them:
Vue.http.post('/dbdata', DataBody).then((response) => {
App.$refs.userContent.rasters_previews_list.$set(response); // putting JSON answer to Component data in userContent
console.log("App.$refs.userContent.rasters_previews_list: ", App.$refs.userContent.rasters_previews_list.length);
}, (response) => {
console.log("Error")
});
Now I am filling. data is declared in var userContent = Vue.extend({. I am using App.$refs.userContent.rasters_previews_list to set it's value, because one man from SO said that there is no other way to get access to constructor. I tried to do output of rasters_previews_list after changing with watch, but here is what I am see. http://img.ctrlv.in/img/16/08/04/57a326e39c1a4.png I really do not understand am I setting it's right way or no. If yes, why I do not see data and see only this crap?
data: function () {
return {
rasters_previews_list: []
}
}
But How I can iterate it with v-for?
<ul v-for="img in rasters_previews_list">
<li>{{img}}</li>
<ul>
This code is display one bullet. So it's look like it's assume that there is one object.
My object in browser console look like:
Object {request: Object, data: Array[10], status: 200, statusText: "OK", ok: true}
Your setting the full response instead of just the data you actually need.
Vue.http.post('/dbdata', DataBody).then((response) => {
App.$refs.userContent.rasters_previews_list.$set(response.data);
console.log("App.$refs.userContent.rasters_previews_list: ", App.$refs.userContent.rasters_previews_list.length);
}, (response) => {
console.log("Error")
});
If this isn't what you are looking for please post a full example.

Sending complex JSON with fetch, save, and delete on a model or collection

We have an internal API that was specifically built to be used with a new piece of software I'm building that runs on Backbone. The API has a single URL and takes JSON as input to determine what it needs to return. It essentially allows me to build custom queries with JSON that return exactly what I'm looking for.
Thing is this JSON can get pretty verbose and is often 3–4 levels deep, but sometimes may just be a few lines and just 1 level deep.
First question first: How do I send a string of JSON along with the ID when I do a fetch()? Do I have to set these parameters as the model or collection's defaults?
Here is an example of a really simple string to get a specific user's info
{
"which" : "object",
"object" : {
"type" : "customer",
"place" : "store",
"customerID" : "14"
}
}
As others have suggested it will likely be challenging to work with SOAP, but it shouldn't be impossible. Backbone models and collections communicate with the server through the sync operation; you should be able to customize that. I think something along these lines might get the ball rolling (for models):
Backbone.SoapyModel = Backbone.Model.extend({
sync: function(method, model, options) {
// force POST for all SOAP calls
method = 'create';
options = _.extend(options, {
// Setting the data property will send the model's state
// to the server. Add whatever complexity is needed here:
data: JSON.stringify({
"which" : "object",
"object" : model.toJSON()
}),
// Set the request's content type
contentType: 'application/json'
});
// Defer the rest to Backbone
return Backbone.sync.apply(this, [method, model, options]);
}
});
var SoapyModelImpl = Backbone.SoapyModel.extend({
url: '/test'
});
var soapTest = new SoapyModelImpl({
id: 42,
name: 'bob',
address: '12345 W Street Dr',
phone: '867 5304'
});
soapTest.fetch();

Knockoutjs validation and server validation

Hi I'm kind of new to Knockoutjs, I am in the scenario where I want to post a form where I have for example an email address, there is an requirement that the email address needs to be unique.
On the server I check if the email address is unique or not and then returns an validationjson class for example
{
isEmailUnique: false,
isPasswordStrongEnough: true;
}
How can I with knockoutjs validation show these errors in a neat way?
I would use two different server side validators for this, since they affect different observables in the view model.
Originally taken from the knockout validation readme
ko.validation.rules['isEmailUnique'] = {
validator: function(val, param){
var isValid = true;
$.ajax({
async: false,
url: '/validation/isEmailUnique',
type: 'POST',
data: { value: val, param: param },
success: function(response){
isValid = response === true;
},
error: function(){
isValid = false; //however you would like to handle this
}
});
return isValid;
},
message: 'The Email is not unique'
};
Then on the server you need to create an endpoint that accepts POST requests where you perform your lookup and then return true or false depending on the result of the query.
To use the above validator
this.email = ko.observable()
.extend({
isEmailUnique: {
message: 'Something else perhaps? It will override the message in the validator'
}
});
You can use the very same thing for the password strength validation.
Using validators like this will fire validation when the observable changes, which can be a useful way to do validation.
I'm a bit late, but for my 2 cents worth, I would take a more generic approach such as returning a standard JSON serialized AjaxResult class from your server endpoints (such as /Register) with properties such as Data (an arbitrary container used for, for example, an updated model to re-bind with the mapping plugin), and a collection of validation message strings, etc. Then you could have an HTML validation summary which is bound to an ObservableArray and push / map the messages from your Ajax result into there. This is essentially what I've been doing with Knockout and it works nicely.