Is there any better solution to convert a form data that is already serialized by jQuery function serialize(), when the form contains multiple input Array fields. I want to be able to convert the form data in to a JSON object to recreate some other informative tables. So tell me a better way to get the serialize string converted as a JSON object.
<form id='sampleform'> <input name='MyName' type='text' /> // Raf <!--array input fields below--> <input name='friendname[]' type='text' /> // Bily <input name='fiendemail[]' type='text' /> // [email protected] <!--duplicated fields below to add more friends --> <input name='friendname[]' type='text' /> // Andy <input name='fiendemail[]' type='text' /> // [email protected] <input name='friendname[]' type='text' /> // Adam <input name='fiendemail[]' type='text' /> // [email protected] </form>
The jquery method applied to get the data
var MyForm = $("#sampleform").serialize(); /** result : MyName=Raf&friendname[]=Billy&fiendemail[][email protected]&friendname[]=Andy&fiendemail[][email protected]&friendname[]=Adam&fiendemail[][email protected] */
how do I make this data in to a JSON object? which should have the following example JSON data from the above form.
{ "MyName":"raf", "friendname":[ {"0":"Bily"}, {"1":"Andy"}, {"2":"Adam"} ], "friendemail":[ {"0":"[email protected]"}, {"1":"[email protected]"}, {"2":"[email protected]"} ] }
jQuery serialize() Method The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.
stringify($("#emails_form"). serializeArray()); If you want to store formData in a JSON file, you need to post it to the server (e.g. per AJAX) and save it. But in that case, you can simply post the form und convert it to JSON on the server itself.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
Data serialization is the process of converting an object into a stream of bytes to more easily save or transmit it. The reverse process—constructing a data structure or object from a series of bytes—is deserialization.
var formdata = $("#myform").serializeArray(); var data = {}; $(formdata ).each(function(index, obj){ data[obj.name] = obj.value; });
Simple and fast ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With