Richardson
Richardson

Reputation: 2285

Submit a form and get a JSON response with Javascript?

any idea how to get a get the JSON response from server after posting a Form I want to post some info, email,pass,confirmation then I want to send the passed email back to frontend. so I can use it later to verify a pin any idea how to grab the response right after posting using JS?

// Backend code 
exports.signUp = async (req, res, next) => {
console.log(req.body);
res.status(200).json({Email : req.body.Email});
})

// Frontend code
 <form class="modal-content" method='POST' action="/sign" >
        <div class="container">
          <hr>
          <label for="email" ><b>Email</b></label>
          <input type="text" placeholder="Enter Email" name="Email">
          <label for="psw"><b>Password</b></label>
          <input id="password" type="password" placeholder="Enter Password" name="Password" required>
          <label for="psw-repeat"><b>Confirm Password</b></label>
          <input id="confirm_password" type="password" placeholder="Confirm Password" name="PasswordConfirm" required>
 </form>
 
 // outgoing data model from Frontend after post
 { Email: '[email protected]', Password: '0', PasswordConfirm: '0' }

Upvotes: 0

Views: 326

Answers (1)

Mister Jojo
Mister Jojo

Reputation: 22320

this way: use FormData

const myForm = document.forms['my-form']

myForm.onsubmit = e =>
  {
  e.preventDefault()
 
  let inputJSON = Array.from(new FormData(myForm))
      .reduce((r,[name,value])=>{ r[name]=value; return r} ,{}) 
    
  console.log(inputJSON) 
  }
<form name="my-form">
  <input name="Email" type="text" placeholder="Enter Email" required> <br>
  <input name="Password"  type="password" placeholder="Enter Password" required> <br>
  <input name="confirm_password" type="password" placeholder="Confirm Password" required> <br>
  <br>
  <button type="submit">submit</button>
  <button type="reset">reset</button>
</form>

Upvotes: 1

Related Questions