-1

I have an HTML form getting user input and I am looking to use client side Javascript to turn the form data into JSON.

See UPDATE below for code~

Assuming the params info is correct, how do I post with JS to the API?

UPDATE:

This is what worked for me:

<div class="uk-width-1-1">
                <p class="uk-button uk-button-default uk-margin" id="demo" onclick="myFunction()">Submit</p>
                </div>

                <script>
                function myFunction() {
                    // Data discovery
                    console.log("Getting info");

                    var d = new Date(); // Now
                    var n = d.getTime(); // getTime for milliseconds since epoch
                    var dateTime = String(n); // Stringifying           
                    var name = document.getElementById("logForm-name").value; // Form data
                    var employee = document.getElementById("logForm-employee").value; // Form data
                    var comments = document.getElementById("logForm-comments").value; // Form data

                    var params = 
                        {
                          "dateID":   dateTime,
                          "visitorName": name,
                          "employeeName": employee,
                          "comments":  comments
                        };
                    JSON.stringify(params); // stringifying

                    // Sending data
                    var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
                    var theUrl = "API URL";
                    xmlhttp.open("POST", theUrl);
                    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                    console.log("Sending...");
                    xmlhttp.send(JSON.stringify(params));
                    document.getElementById("demo").style.color = "green"; // Visual for success
                    console.log("Item added to DDB.");

                    // Reset Form
                    document.getElementById('logForm').reset()
                }
                </script>
mcspadden
  • 95
  • 3
  • 9
  • Do you want to do an ajax request? Is that it? https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest – Vitor Rigoni Jul 05 '19 at 05:33
  • I would like to POST the JSON data to the API, is that the same? lol @VitorRigoni – mcspadden Jul 05 '19 at 05:38
  • Well, yeah, doing an ajax request is one way of doing that. There are many questions like this here in SO: https://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery – Vitor Rigoni Jul 05 '19 at 05:41

1 Answers1

0

use xmlHTTPrequest to do call post data from body. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest