Well, you can use jQuery for it as it is easy to use and less code to write. Though i am giving both solutions here.
In JavaScript :
$.fn.extractObject = function() {
var accum = {};
function add(accum, namev, value) {
if (namev.length == 1)
accum[namev[0]] = value;
else {
if (accum[namev[0]] == null)
accum[namev[0]] = {};
add(accum[namev[0]], namev.slice(1), value);
}
};
this.find('input, textarea, select').each(function() {
add(accum, $(this).attr('name').split('.'), $(this).val());
});
return accum;
}
// ...
var object = $('#testformId').extractObject();
console.log(object);
In jQuery :
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});
(jQuery portion taken from here)
for posting the data to php through javascript:
var str_json = JSON.stringify(myObject) //gives me the JSON string.
// AJAX XMLHttpRequest object in Javascript to send data to the server:
request= new XMLHttpRequestObject()
request.open("POST", "Phppage.php")
request.setRequestHeader("Content-type", "application/json", true)
request.send(str_json)