Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

html form post json example

submitButton.addEventListener("submit", (event) => {
  const formData = new FormData(event.target);
  // object used to collect form data
  const objToSend = new Object();
  formData.forEach((value, key) => {
    if (!Reflect.has(objToSend, key)) {
      // property key encountered for first time
      Reflect.set(objToSend, key, value);
    } else {
      if (!Array.isArray(objToSend[key])) {
        // convert value into array
        objToSend[key] = [objToSend[key]];
      }
      // add new value to array
      objToSend[key].push(value);
    }
  });
  // Stringify object holding form data
  const objAsJSON = JSON.stringify(objToSend);
  console.log(objAsJSON);
});
 
PREVIOUS NEXT
Tagged: #html #form #post #json
ADD COMMENT
Topic
Name
8+3 =