I have a form in my HTML that collects user input, and I want to convert the form data into JSON using client-side Javascript.
Check out the code update below~
If the params information is accurate, how can I use JavaScript to post to the API?
UPDATE:
Here is the solution that 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 extraction
console.log("Retrieving information");
var d = new Date(); // Current date
var n = d.getTime(); // Milliseconds since epoch
var dateTime = String(n); // Converting to string
var name = document.getElementById("logForm-name").value; // Form field data
var employee = document.getElementById("logForm-employee").value; // Form field data
var comments = document.getElementById("logForm-comments").value; // Form field data
var params =
{
"dateID": dateTime,
"visitorName": name,
"employeeName": employee,
"comments": comments
};
JSON.stringify(params); // Converting to string
// Sending data
var xmlhttp = new XMLHttpRequest(); // Creating 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 feedback for success
console.log("Item added to Database.");
// Resetting form
document.getElementById('logForm').reset()
}
</script>