すべての出会いが美しいとは限らない。すべての別れが悲しいとは言えない。

0%

Get form data to json

Sometimes we need get the form data as a json to put it into another ajax request with other data.
This is a method to get the data of form as json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function getFormJson(name) {
var data = {};
var form_data = $(name).serializeArray()
for (var i = 0; i < form_data.length; i++){
if (data[form_data[i]['name']] != undefined) {
if ($.isArray(data[form_data[i]['name']])) {
data[form_data[i]['name']].push(form_data[i]['value']);
} else {
data[form_data[i]['name']] = [data[form_data[i]['name']], form_data[i]['value']];
}
} else {
data[form_data[i]['name']] = form_data[i]['value'];
}
}
return data;
}