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")
}
});
Related
I'm trying to send images from my form to my php webservice.
For now, I'm just trying to see if i receive it well.
and with this code:
html:
<input type="file" multiple name="images" id="images" />
<button class="bouton" id="valider">envoi</button>
Js:
const sample_image = document.getElementById('images');
const valider = document.getElementById('valider');
valider.addEventListener('click', () => {
upload_image(sample_image.files[0]);
})
const upload_image = (file) => {
const form_data = new FormData();
form_data.append('sample_image', file);
console.log(form_data);
fetch(host+"add.php", {
method: "POST",
body:form_data
}).then(response => response.json())
.then(response => {
console.log(response);
});
}
Php:
echo json_encode($_FILES['sample_image']);
It's working but only for 1 image, but i need send many.
and when i try to change my JS to :
upload_image(sample_image.files);
(without the [0])
it's not working.
I just wanted to send an array of files and then use it in my php, but it says
Notice: Undefined index: sample_image
Does it exists a way to do it ?
Thank you.
it's working with :
const upload_image = (files) => {
const form_data = new FormData();
let compt = files.length;
for(let i=0;i<compt;i++)
{
form_data.append('sample_images[]', files[i]);
}
console.log(files.length);
console.log(form_data);
fetch(host+"add.php", {
method: "POST",
body:form_data
}).then(response => response.json())
.then(response => {
console.log(response);
}); }
thank you everyone !
You need to change the FormData to receive an array instead of a single item:
const upload_image = (files) => {
const form_data = new FormData();
form_data.append('sample_images[]', files);
console.log(form_data);
fetch(host+"add.php", {
method: "POST",
body:form_data
}).then(response => response.json())
.then(response => {
console.log(response);
}); }
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>
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
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
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")}}`
);