Search code examples
javascripthtmlnode.jspostgresqlgetelementbyid

getElementById.value to json into PostgreSQL with node.js, won't pass value


Well, I need some help with my app.

I'm trying to pass a value which I get from an getElemenyById() on my HTML but when the code runs it won't go into my database.

When I show the value through an Alert() I see the json values correctly but they won't go to the database.

If I manually input the value instead of using the getElementById().value, the code works correctly.

I'll leave some key parts of my code, thanks in advance. Any help is appreciated!

        <script>
            const btnCreate = document.getElementById("btn");
            btnCreate.addEventListener("click", async e=> {
                const jsonRequest = {};

                jsonRequest.id = document.getElementById("status").value;
                jsonRequest.lead_id = document.getElementById("brandname").value;
                alert("id = "+jsonRequest.id+" && lead_d = "+jsonRequest.lead_id);

                const result = await fetch("http://localhost:8080/lds", {method: "POST",
                    headers: {"content-type": "application/json"}, body: JSON.stringify(jsonRequest) });
                const success = await result.json();
                alert("CREATED! ")

            })
        </script>
app.post("/lds", async (req, res) => {
    let result = {}
    try{

        const reqJson = req.body;
        await createStatus(reqJson.id,reqJson.lead_id);
        result.success = true;
    }
    catch(e){
        result.success = false;
    }

    finally{
        res.setHeader("content-type", "application/json")
        res.send(JSON.stringify(result))
    }

})
async function createStatus(id, lead_id) {

    try {
        await client.query("insert into lead_status (id, lead_id) values ($1, $2)", [id, lead_id]);
        return true
    } catch (e) {
        return false;
    }
}

Solution

  • Well that was quick,

    I think I found an answer to my issue though I'm not sure if its correct. What I'm sure is that it works.

    The problem was on the js on the html script. I just parsed the getElementById().valueas int.

    Both fields in my db table are integers.

    
    parseInt(jsonRequest.id = document.getElementById("brandname").value);
    parseInt(jsonRequest.lead_id = document.getElementById("status").value);