POST javascript variable to JSON on form submit - javascript

I need to have number format passed to JSON and I cannot use input type hidden because it returns string. I have const formDataJsonString = JSON.stringify(plainFormData); to translate form data to JSON (see below)
How do I POST javascript variable from form into JSON with the functions that I added below?
I have written this to convert it into number but have no clue on how to submit the javascript variable to JSON.
<input type="hidden" class="number" name="applicationType" value=3>
$("#form").submit(function(){
var formInfo = document.forms['form'];
var applicationType = parseInt($(".number").val());
});
The desired result in JSON:
applicationType: 3
Instead of:
applicationType: "3"
UPDATE 1:
So I have this to make it into JSON, and then POST it:
//url is the api
async function postFormDataAsJson({ url, formData }) {
const plainFormData = Object.fromEntries(formData.entries());
//put all accountsToLink value into an array
plainFormData["accountsToLink"] = new Array //create array
$("input[name=accountsToLink] ").each(function() {
plainFormData["accountsToLink"].push($(this).val()) //push value in array
});
const formDataJsonString = JSON.stringify(plainFormData);
const fetchOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: formDataJsonString,
};
const response = await fetch(url, fetchOptions);
if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
else if (response.ok) {
window.location.href = "confirmation.html";
}
return response.json();
}
async function handleFormSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
const url = form.action;
try {
const formData = new FormData(form);
const responseData = await postFormDataAsJson({ url, formData });
console.log({ responseData });
} catch (error) {
console.error(error);
}
}
const testform = document.getElementById('testform');
testform.addEventListener('submit', handleFormSubmit);

So you failed to mention you do NOT do what you did in the initial post but instead you use formData
You cannot use formData to JSON integers.
You can map a serialized array and stringify that
async function postFormDataAsJson({ url, formData }) {
const formDataJsonString = JSON.stringify(formData);
console.log(url,formDataJsonString)
// ....
}
async function handleFormSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
const url = form.action;
try {
const formData = $(form).serializeArray().map(
item => ({ [item.name]: isNaN(item.value) ? item.value : +item.value})
);
const responseData = await postFormDataAsJson({ url, formData });
} catch (error) {
console.error(error);
}
}
$("#testform").on("submit", handleFormSubmit);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="testform" action="/bla.php">
<input type="hidden" class="number" name="applicationType" value=3>
<input type="submit" />
</form>

Related

Can't get the proper object back

Hi i'm using MeaningCloud's api to get the proper object back once it analyses a string of text or a url for the Natural language processing (NLP). But it doesn't return the proper object.
Right now the code returns a string with the text "[Object object]" on the HTML page. I need it to return the results of the api call which returns the proper JSON object(that I can see in the console) in a proper "key/value" pair format on the HTML page.
Here's my script:
const baseURL = "https://api.meaningcloud.com/sentiment-2.1";
const key = "Your_api_key";
const submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click", (e) => {
e.preventDefault();
const url = document.getElementById("url").value;
if (url !== "") {
getData(baseURL, url, key)
.then(function (data) {
postData("/add", { data: data });
}).then(function () {
receiveData()
}).catch(function (error) {
console.log(error);
alert("Invalid input");
})
}
})
const getData = async (baseURL, url, key) => {
const res = await fetch(`${baseURL}?key=${key}&txt=${url}`)
try {
const data = await res.json();
return data;
}
catch (error) {
console.log("error", error);
}
}
const postData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data: data
})
});
try {
const newData = await response.json();
return newData;
} catch (error) {
console.log(error);
}
};
const receiveData = async () => {
const request = await fetch('/all');
try {
// Transform into JSON
const allData = await request.json()
console.log(allData)
// Write updated data to DOM elements
document.getElementById('result').innerHTML = allData;
}
catch (error) {
console.log("error", error);
// appropriately handle the error
}
}
I have another main file that's the server.js file which I run using node server.js that renders the html page properly but the script doesn't render the results on the page properly. You can signup on meaningcloud for a free api key that has a very convenient number of calls you can make.

How do I Add Text to a form pull

So I'm trying to make an API Fetch from a Form Input (The Search bar of my site), I Want to add Text to whatever was inputted to the Text Field and then send it trough to be pulled.
<form id="SearchBoxMainNav" style="display: flex;">
<input class="nav-button" type="submit" name="search" value="" >
<input id="SearchTerm" type="search" class="search" name="search" value="" placeholder="I Draw...!" autocomplete="off" />
</form>
Java Script
const apiUrl = 'https://db.ygoprodeck.com/api/v7/cardinfo.php';
SearchBoxMainNav.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(SearchBoxMainNav);
const formDataSerialized = Object.fromEntries(formData);
const jsonObject = { ...formDataSerialized};
console.log(formDataSerialized, "formDataSerialized");
try {
const response = await fetch(apiUrl, {
method: 'POST',
body: JSON.stringify("fname" + jsonObject),
Headers: {
'Contnent-Type': 'application/json'
},
});
const json = await response.json();
console.log(json);
} catch(event) {
console.error(event)
alert("there was an Error")
}
});
so what I Would like to do is as they submit it Text is added to the Front and then It goes trough the whole javascript Prosccess
Concatenate the text with jsonObject.search, not jsonObject.
Object.fromEntries() returns a new object, there's no need to duplicate it with {...formDataSerialized}
const apiUrl = 'https://db.ygoprodeck.com/api/v7/cardinfo.php';
SearchBoxMainNav.addEventListener('submit', async(event) => {
event.preventDefault();
const formData = new FormData(SearchBoxMainNav);
const jsonObject = Object.fromEntries(formData);
jsonObject.search = 'fname ' + jsonObject.search;
try {
const response = await fetch(apiUrl, {
method: 'POST',
body: JSON.stringify(jsonObject),
Headers: {
'Content-Type': 'application/json'
},
});
const json = await response.json();
console.log(json);
} catch (event) {
console.error(event)
alert("there was an Error")
}
});

how can i submit form data and file using fetch in react?

At first, the task was set to send data from the form. The problem was solved in the following way:
export let useRequest = () => {
let request = async (url, method = "Post", body = null, headers = {}) => {
try {
if (body) {
body = JSON.stringify(body);
headers["Content-Type"] = "application/json";
}
let res = await fetch(url, { method, body, headers });
let data = await res.json();
return data;
} catch (e) {
throw e;
}
};
form:
<form>
<input name="name" class="help-input" placeholder="name" type="text" value=""/>
<input name="email" class="help-input" placeholder="email" type="text" value=""/>
<textarea name="message" class="help-input"placeholder="message"></textarea>
<input name="file" type="file" value="">
<input name="agree" type="checkbox" value="" checked/>
<button type="submit" onClick="props.send">send</button>
</form>
Form container(form wrapper):
export let HelpBlock = (props) => {
let { request } = useRequest();
let reqFromForm = async (values) => {
let data = await request("/api/message", "POST", props.values);
console.log(data.message)
};
return (
<>
<Form send={reqFromForm}></Form>
</>
);
};
After clicking on the button, data comes with the following structure:
{
name:name,
email:email,
message:message,
file:file
}
In this case I think that you can render the body according to the content type:
export let useRequest = () => {
let request = async (url, method = "Post", body = null, headers = {}, contentType="application/json" ) => {
try {
if (body) {
body = renderBodyFormat(body, contentType);
headers["Content-Type"] = contentType;
}
let res = await fetch(url, { method, body, headers });
let data = await res.json();
return data;
} catch (e) {
throw e;
}
};
return { request };
};
const renderBodyFormat = (data, type) => {
const formats = {
"application/json": ()=> JSON.stringify(body),
"multipart/form-data": ()=> {
const form = new FormData();
Object.keys(data).forEach(key => form.append(key, data[key]));
return form;
}
}
return formats[type]();
}
EDIT: //using the hook:
const Component = ()=> {
const {request} = useRequest();
useEffect(()=> {
const data = {
//...other props
file: new File(["file"], "file.txt", { type: "text/plain"});
}
request(url, "Post", data, {}, "multipart/form-data")
.then(()=> {
//...
})
})
}
Here you can find more info https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

form value seems to be blank while sending through fetch

const fetch = require('node-fetch');
const FormData = require('form-data');
async function check () {
const form = new FormData();
form.append('merchantIdentifier', 'b19e8f103bce406cbd3476431b6b7973')
form.append('orderId', 'ZPK12345' )
form.append('mode', 0)
form.append('checksum', '94681259256bc24e3c6881fe85e0fd61cf1b41a0e650c9ca6b7b7fe7ae510af4')
try {
const result = await fetch(`http://zaakpaystaging.centralindia.cloudapp.azure.com:8080/checktransaction?v=5`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: form
})
const data = await result.text()
console.log(data)
} catch (error) {
console.log(error);
}
}
check()
sending data to http://zaakpaystaging.centralindia.cloudapp.azure.com:8080/checktransaction?v=5 through form data but response form value is null

array to objects in a react.js form

I have a form code that the api is a PUT method, I have a part where I have to send it in the form of a objects, but when I send it it sends it to me as an array, they also tell me that I have to send them if it is true or false
handleSubmit = async (event) => {
const {
state,
city,
mild_symptoms = [],
} = event
const YES = "Si"
console.log(event)
try {
const myHeaders = new Headers();
const url =
"XXXXXXXXX";
myHeaders.append(
"x-api-key",
"XXXXX"
);
myHeaders.append("state", state);
myHeaders.append("city", city);
myHeaders.append(
"mild_symptoms",
`{"flu_syndrome": ${mild_symptoms.includes("flu_syndrome")}, "conjunctivitis": ${mild_symptoms.includes("conjunctivitis")}, "muscle_pain": ${mild_symptoms.includes("muscle_pain")}}`
);
var requestOptions = {
method: "PUT",
headers: myHeaders,
mode: "cors"
};
const response = await fetch(url, requestOptions);
console.log("FIRST RESPONSE ", response);
const result = await response.text();
console.log("RESULT", result);
Modal.success({
title: "Éxito",
content: "Datos enviados correctamente",
onOk: ()=>{
window.location.href = "https://covid19.gob.sv/orientaciones-tecnicas/"
}
})
} catch (error) {
console.log("ERROR", error);
}
I have to send this as a objects and not as an array
"mild_symptoms",
`{"flu_syndrome": ${mild_symptoms.includes("flu_syndrome")}, "conjunctivitis": ${mild_symptoms.includes("conjunctivitis")}, "muscle_pain": ${mild_symptoms.includes("muscle_pain")}}`
);

Categories