I have a task to do with pure JavaScript and I came up to a problem when writing data to API file. This is what I wrote:
document.getElementById('btn').addEventListener("click",function (event) {
event.preventDefault();
var countryName = document.getElementById("name").value;
var countryArea = document.getElementById("area").value;
var countryPopulation = document.getElementById("population").value;
var countryCallingCode = document.getElementById("calling_code").value;
if (countryName !== "" && countryArea !== "" && countryPopulation !== "" && countryCallingCode !== "") {
var postReq = new XMLHttpRequest();
postReq.open('POST', '', true);
var data = {
area: countryArea,
calling_code: countryCallingCode,
created_at: Date.now(),
id: ID,
name: countryName,
population: countryPopulation
};
console.log(data.id);
var jsonPost = JSON.stringify(data);
postReq.onload = function () {
var countries = JSON.parse(postReq.responseText);
if (postReq.readyState == 4 && postReq.status == "201") {
console.log(countries);
}
}
postReq.send(jsonPost);
}
});
But I receive an error of POST 422 (Unprocessable Entity)
. I wrote get, delete and edit functions too and they work, so I don't understand why this one doesn't work. So maybe someone know why this happens and how to fix this problem?
This is an example code, that is working for me:
var data = {};
data.area = 5555;
data.calling_code = "+25";
data.name = "Japan";
data.population = 100000000;
var url = "";
var jsonUpdate = JSON.stringify(data);
console.log(jsonUpdate);
var updateReq = new XMLHttpRequest();
updateReq.open("PUT", url + '/3', true);
updateReq.setRequestHeader('Content-type', 'application/json; charset=utf-8');
updateReq.onload = function () {
var countries = JSON.parse(updateReq.responseText);
if (updateReq.readyState == 4 && updateReq.status == "200") {
console.table(countries);
} else {
console.error(countries);
}
}
updateReq.send(jsonUpdate);