huwred
08/19/2024, 9:04 AMasync function updatePoll(formdata: FormData) {
const apiAddress = "/post-question";
const headers: Headers = new Headers();
headers.set('Content-Type', 'application/x-www-form-urlencoded');
const response = await fetch(apiAddress, {
method: 'POST',
headers: headers,
body: JSON.stringify(Object.fromEntries(formdata))
,
});
const data = await response.json();
if (response.ok) {
console.log(data);
}
}
I'm currently sending a string as could not figure out how to handle the formData object in the controller
I can hit my controller method and extract the json string from the body, so it definitely all works. Seems a bit hacky, so wondered if anyone else had done something simiar?
The data does not come from umbraco, it comes from some custom tables.huwred
08/20/2024, 7:19 AMhuwred
08/20/2024, 7:29 AMjs
private async updatePoll(formdata: FormData) {
const value = Object.fromEntries(formdata.entries());
const answers = formdata.getAll("Answers");
const sort = formdata.getAll("answerssort");
const ids = formdata.getAll("answersid");
//construct the answers json array
let answersString = '[';
for (var i = 0; i < answers.length; i++) {
answersString += '{"Id":'+ ids[i] +',"Value":"'+ answers[i] +'","Index":'+ sort[i] +' }';
if (i < answers.length - 1) {
answersString += ',';
}
}
answersString +=']';
//update value
value.Answers = JSON.parse(answersString);
const jsonstring = JSON.stringify(value);
const headers: Headers = new Headers();
headers.set('Content-Type', 'application/json');
const response = await fetch("/post-question", {
method: 'POST',
headers: headers,
body: jsonstring
,
});
const data = await response.json();
if (response.ok) {
//do something with the results
console.log(data);
}
}
}
A hub and casual space for you to interact with fellow community members and learn more about Umbraco!
Powered by