How to send a JSON object using html form data
So I’ve got this HTML form:test
Which would be the easiest way to send this form’s data as a JSON object to my server when a user clicks on submit?
I’ve gone as far as this but it doesn’t seem to work:
contentType : "application/json"
HTML provides no way to generate JSON from form data.
- gather your data from the form via DOM
- organise it in an object or array
- generate JSON with JSON.stringify
- POST it with XMLHttpRequest
You'd probably be better off sticking to
application/x-www-form-urlencoded data and processing that on the server instead of JSON. Your form doesn't have any complicated hierarchy that would benefit from a JSON data structure.
Update in response to major rewrite of the question…
- Your JS has no
readystatechange handler, so you do nothing with the response
- You trigger the JS when the submit button is clicked without cancelling the default behaviour. The browser will submit the form (in the regular way) as soon as the JS function is complete.
you code is fine but never executed, cause of submit button [type="submit"]
just replace it by type=button
<input value="Submit" type="button" onclick="submitform()">
inside your script;
form is not declared.
let form = document.forms;
xhr.open(form.method, form.action, true);