1

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);
Ali G.
  • 13
  • 1
  • 6
  • 1
    [422 - unprocessable entity](https://httpstatuses.com/422) means that the data you are posting to the server is considered malformed or otherwise invalid. – JJWesterkamp Jul 19 '19 at 16:56
  • 1
    We see what data you are posting but we cannot see what server side is expecting. Can you attach example of data from `GET` method that is working for you? – andy Jul 19 '19 at 17:25
  • @andy I attached ```PUT``` method, because it is much shorter than my ```GET ``` method but this works too. – Ali G. Jul 19 '19 at 17:45
  • Difference is that you `POST` data with `created_at` attribute extra comparing to `PUT` – andy Jul 19 '19 at 17:47
  • I am trying now to change the input, trying to save data as it is in an example array but still the same problem :( https://i.paste.pics/cac36257325ae9741d8ba9f90cc214fd.png the bottom array is what I wrote – Ali G. Jul 19 '19 at 17:49
  • @andy I changed it. Now it looks like this but still the same problem: https://codepen.io/eglyyt/pen/eqOjMv/?editors=1010 – Ali G. Jul 19 '19 at 17:51
  • 1
    Now client side options and guesswork ends. What is swagger for service you are calling. If missing descriptor do you have working data samples? If not then blame server itself or lack of its documentation. – andy Jul 19 '19 at 19:35
  • @andy I have samples and I tried following them but the error keeps popping up. This is one of the samples: https://paste.pics/0e541d9e2fa8ffda217d8597f8d0d467 – Ali G. Jul 19 '19 at 20:11
  • 1
    Ok, so now you need crystal ball :) seriously talk to service owner to get some guidance. There is too many variables in equation to solve – andy Jul 19 '19 at 21:17

1 Answers1

1

Your created_at is served as formatted date string (on attached screenshot) like "2019-07-19 19:53" while you are POSTing Date.now() that is a number like 1563558732238. You need to format Date object to human-readable form with same pattern and your server should be ok.

EDIT: further investigation shows that even correct looking data does not pass 422 - server side service owner must be contacted :/

andy
  • 757
  • 5
  • 13
  • I changed it and it is still the same. Here is the code now: https://codepen.io/eglyyt/pen/wVBNRp?editors=0010 – Ali G. Jul 19 '19 at 18:00
  • https://paste.pics/03b9a747badf42e34c723428f5a60db0 this is what I input – Ali G. Jul 19 '19 at 18:02
  • You are also posting `id` set to `ID` a variable that does not occur in your code, so it post `id: null` effectively. Will your `PUT` method work when you add `id: null` to posted data? – andy Jul 19 '19 at 18:06
  • I forgot to mention about it but the ID occurs in my code, I save it globally after reading the data, the ID is a length of the array, so everytime the amount of rows increases in the array the ID increases too. – Ali G. Jul 19 '19 at 18:11
  • So servers side is also yours? Can you share server code for POST and PUT, please? – andy Jul 19 '19 at 19:39
  • Maybe I expressed it badly, but server is not mine :( – Ali G. Jul 19 '19 at 20:07