How to send a JSON object using html form data
Get complete form data as array and json stringify it.
var formData = JSON.stringify($("#myForm").serializeArray());
You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it. You'll then get all data in an array.
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
How to convert FormData (HTML5 object) to JSON
You could also use forEach
on the FormData
object directly:
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
UPDATE:
And for those who prefer the same solution with ES6 arrow functions:
var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);
UPDATE 2:
And for those who want support for multi select lists or other form elements with multiple values (since there are so many comments below the answer regarding this issue I will add a possible solution):
var object = {};
formData.forEach((value, key) => {
// Reflect.has in favor of: object.hasOwnProperty(key)
if(!Reflect.has(object, key)){
object[key] = value;
return;
}
if(!Array.isArray(object[key])){
object[key] = [object[key]];
}
object[key].push(value);
});
var json = JSON.stringify(object);
Here a Fiddle demonstrating the use of this method with a simple multi select list.
UPDATE 3:
As a side note for those ending up here, in case the purpose of converting the form data to json is to send it through a XML HTTP request to a server you can send the FormData
object directly without converting it. As simple as this:
var request = new XMLHttpRequest();
request.open("POST", "http://example.com/submitform.php");
request.send(formData);
See also Using FormData Objects on MDN for reference:
UPDATE 4:
As mentioned in one of the comments below my answer the JSON stringify
method won't work out of the box for all types of objects. For more information on what types are supported I would like to refer to the Description section in the MDN documentation of JSON.stringify
.
In the description is also mentioned that:
If the value has a toJSON() method, it's responsible to define what data will be serialized.
This means that you can supply your own toJSON
serialization method with logic for serializing your custom objects. Like that you can quickly and easily build serialization support for more complex object trees.
How to post form data as JSON?
There's a couple problems here.
Invalid start tag for script element. This was probably a copy and paste error, but worth mentioning:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>
missing greater than symbol ^Selecting
register_form
instead of#register_form
in two places, the second was unnecessary regardless because you could referencethis
instead. This also resulted in the form submission not being cancelled.You didn't include a
$.serializeJSON
plugin, again I'm assuming this is a copy and paste error.$.serializeJSON
(whichever you choose) should return a JSON string, but you runJSON.stringify
on the result, which will be a string inside a string.https://https://
This isn't a huge issue because it is in theaction
attribute of a form that should never submit, but worth mentioning.
In the example below I've provided a simple replacement for $.serializeJSON
, and corrected the rest of the issues listed above. serialize_form
in the code below can be replaced with whatever $.serializeJSON
plugin you choose to use.
I have commented out the ajax request as what is really of concern here is getting the JSON from the form data, so I just log it to the console instead so that you can see it is a JSON string. I also removed the pattern attributes and required flags from the input for ease of testing.
const serialize_form = form => JSON.stringify( Array.from(new FormData(form).entries()) .reduce((m, [ key, value ]) => Object.assign(m, { [key]: value }), {}));
$('#register_form').on('submit', function(event) { event.preventDefault(); const json = serialize_form(this); console.log(json); /*$.ajax({ type: 'POST', url: 'https://url.com/users/register', dataType: 'json', data: json, contentType: 'application/json', success: function(data) { alert(data) } });*/});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><form id="register_form" action="https://url.com/users/register" method="post"> <input type="text" placeholder="Name" name="name" title="Up to 20 alphabetical characters"> <input type="email" placeholder="Email" name="email" title="Must be a valid email address"> <input type="password" placeholder="Password" name="password" title="Must be 8 or more characters long and contain at least one number and one uppercase letter"> <input type="text" placeholder="Homeadress" name="homeadress"> <input type="text" placeholder="Postnumber" name="postnumber"> <input type="text" placeholder="City" name="city"> <br> <button value="Submit" type="submit">Register</button></form>
Post JSON data in a HTML form
HTML form input fields should have a name
attribute to be accepted, otherwise they are ignored in the form submission. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
The above work with the following change:
...
// added name attribute
<textarea name="reqData" defaultValue={JSON.stringify({ collection, fieldSets, responseType: 'csv' })} />
...
Related Topics
How to Make a ≪Button≫ Not Submit a Form
How to Programmatically Set the Value of a Select Box Element Using JavaScript
Is There a Spec That the Id of Elements Should Be Made Global Variable
Get Dom Content of Cross-Domain Iframe
Submit Two Forms With One Button
What Does "./" (Dot Slash) Refer to in Terms of an HTML File Path Location
Get File Size, Image Width and Height Before Upload
How to Escape HTML Special Chars in JavaScript
Get Cursor Position (In Characters) Within a Text Input Field
Adjust Width and Height of Iframe to Fit With Content in It
Height Equal to Dynamic Width (Css Fluid Layout)
In What Situations Would Ajax Long/Short Polling Be Preferred Over Html5 Websockets
How to Check File Mime Type With JavaScript Before Upload
Creating a Div Element in Jquery
How to Specify a Suggested Filename When Using Data: Uri
Get Class List For Element With Jquery
Performance of Mutationobserver to Detect Nodes in Entire Dom