I want to convert all form values to JSON so that I can send the JSON as body in my AJAX POST. I found this existing solution online:
function getFormData($form){
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
Usage:
var $form = $("#form_data");
var data = getFormData($form);
However, this approach (source) converts all values to type string, it does not preserve numbers as integers. I could not come up with a way to preserve the type of the values. What is the best way to do this?
HTML:
<form id="myform">
<div>
<label>Number: </label>
<input id="mynum" type="number" name="mynum"/>
</div>
<div>
<label>name: </label>
<input id="myname" type="text" name="myname"/>
</div>
</form>