Reputation: 5533
Having 2 issues submitting a form as JSON via jQuery .ajax method fiddle is here. Using my current function to get the form data, I get the error 'Uncaught TypeError: Converting circular structure to JSON' and believe it is due to submitting a date from a date picker in the form.
From json.org : "A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested."
I can't seem to get the format right either, I need to submit the data like this:
{
"type": "value",
"identification": {
"ssn": "value"
},
"date_of_birth": "value",
"name": {
"first": "value",
"middle": "value",
"last": "value"
},
"address": {
"street1": "value",
"street2": "value",
"city": "value",
"state": "value",
"postal_code": "value",
"country_code": "value"
}
}
and not sure how to get the nested parent, child and grandchild nesting. Here is my convert to JSON funciton:
function ConvertFormToJSON(form) {
var array = $(form).serializeArray();
var json = {};
$.each(array, function(){
json[this.name] = this.value || '';
});
return json;
}
and here is my attempt at the submission
$('#USForm').validate({
errorLabelContainer: "ul#msgBox",
wrapper: "li",
submitHandler: function(form) {
var form = this;
var json = ConvertFormToJSON(form);
$.ajax({
type:'POST',
url:'http://ec2-54-201-216-39.us-west-2.compute.amazonaws.com/testc/WebService.asmx?op=VerifyIdentityJson',
crossDomain:true,
data: json,
dataType : 'json'
})
.always(function(){
console.log("always:" + json);
})
.done(function (response){
console.log("done:" + json);
})
.fail(function(){
console.log("fail" + json);
});
return false;
},
rules: {
//rules
},
messages: {
//messages
});
Upvotes: 1
Views: 202
Reputation: 144689
The first parameter (form) returns the validator
instance for me. The currentForm
property of it gives you the current form
element.
For creating the JSON structure I would suggest using identifiers for grouping the form controls, I have used data-group
attribute in the following demo:
<input type="hidden" data-group="address" name="country_code" id="country_code" value="US">
Then you can create an object using a loop:
// Please do not use a StudlyCase name for a non-Constructor function
function ConvertFormToJSON(form)
{
var elems = [].slice.call(form.elements);
var o = {};
$.each(elems, function() {
var $this = $(this),
g = $this.data('group');
// if the current element has data-group attribute
if (g) {
// if the object doesn't have `group` property yet
// create an object so we can set a property to it later
if ( !o.hasOwnProperty(g) ) {
o[g] = {};
}
o[g][this.name] = this.value;
} else {
// otherwise set a top level property
o[this.name] = this.value;
}
});
return o;
}
Please note that I have manipulated the rules
property just for passing validation.
Upvotes: 1