I'm sending data from a form with a variable number of fields via an Ajax call. Some of the fields are grouped together so I have opted to send them as an array of JSON objects to keep the groupings, but there are a number of ways of doing this. For client-side, is it better to read the form as JavaScript objects and stringify them or just directly work with strings from the start?
Here's an example:
I want to group the data so I know which date goes with which member, so I have created a bunch of objects and added them to an array. This seems to work but there are issues with using JSON.stringify
because it's not supported in IE7. I don't know if modifying the form is very efficient either. How would you manage this? Or would you submit the form as is and sort it out on the server? What's the most widely accepted approach?
HTML:
<form id="form">
<h3>Group Name</h3>
<input type="text" name="group_name"><br>
<h3>Members</h3>
<button type="button">New member</button>
<br><label for="name">Name</label><label for="date">Date</label>
<div id="dynamic_form">
<span class="member_data"><input type="text" name="name"><input type="text" name="date"></span><br>
</div>
<input type="submit">
</form>
<div id="member_info"></div>
JavaScript:
$(document).ready(function(){
$('#form').submit(function(e){
var memberArr = [];
$('.member_data').each(function(){
var thisMember = {};
$(this).children().each(function(){
thisMember[$(this).attr('name')] = $(this).val();
});
memberArr.push(thisMember);
// Delete this input
$(this).remove();
});
var input = $("<input>").attr("type", "hidden").attr("name", "members").val(JSON.stringify(memberArr));
$('#dynamic_form').append($(input));
e.preventDefault();
$.post("http://geraintanderson.com/cgi-bin/ajax_array.py",
$('#form').serialize(),
function(data, status){
$('#member_info').html(data);
// Reset the form
$('#dynamic_form').html('<span class="member_data"><input type="text" name="name"><input type="text" name="date"></span><br>');
});
});
$('button').click(function(){
// Add new form fields
$('#dynamic_form').append('<span class="member_data"><input type="text" name="name"><input type="text" name="date"></span><br>');
});
});
And here's a live example using a Python script to return some text.