I have tried jQuery('#form_id').serialize()
. This returns only the form data as a url encoded string. Is it possible to get the form data as an object?
Asked
Active
Viewed 1.1e+01k times
64
-
Have you check this : https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery/39248551#39248551 – Bhavik Hirani Mar 26 '18 at 08:00
2 Answers
106
Have you tried "serializeArray"? That gives you an array of names and values. You could turn that into an object if you wanted to:
var paramObj = {};
$.each($('#myForm').serializeArray(), function(_, kv) {
paramObj[kv.name] = kv.value;
});
(I'll have to check again to see what jQuery does with arrays; I think it encodes them as Javascript array values, but I'm not 100% sure.)
edit ah no, it doesn't set up multi-valued parameters as arrays - you get repeats of the same name. Thus, the make-an-object code should look like this:
var paramObj = {};
$.each($('#myForm').serializeArray(), function(_, kv) {
if (paramObj.hasOwnProperty(kv.name)) {
paramObj[kv.name] = $.makeArray(paramObj[kv.name]);
paramObj[kv.name].push(kv.value);
}
else {
paramObj[kv.name] = kv.value;
}
});
(or something like that; could probably be squeezed a little.)

Pointy
- 405,095
- 59
- 585
- 614
35
You may take a look at the serializeArray function:
$('#form_id').serializeArray()

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928