I have a very plex form in a web page. User actually builds up a plex object. The UI is handled using jQuery (showing, hiding sections, duplicating and deleting sub-forms,...).
Simply posting the form upon user submission, although possible, doesn't seem the best solution: It would be hard to makeup unique names for fields (there can be arrays of objects) and to decode the whole stuff on server side.
I guess I should rather post a JSON representation of the object. How do I do that?
I'm not trying to make an ajax call. I want to submit the form but using JSON instead of an usual application/x-www-form-urlencoded form.
FWIW, the backend is ASP.NET MVC.
TIA,
I have a very plex form in a web page. User actually builds up a plex object. The UI is handled using jQuery (showing, hiding sections, duplicating and deleting sub-forms,...).
Simply posting the form upon user submission, although possible, doesn't seem the best solution: It would be hard to makeup unique names for fields (there can be arrays of objects) and to decode the whole stuff on server side.
I guess I should rather post a JSON representation of the object. How do I do that?
I'm not trying to make an ajax call. I want to submit the form but using JSON instead of an usual application/x-www-form-urlencoded form.
FWIW, the backend is ASP.NET MVC.
TIA,
Share Improve this question asked Mar 2, 2011 at 11:13 Serge WautierSerge Wautier 21.9k13 gold badges72 silver badges113 bronze badges 1- 1 Have you solved out this question? – Achilleterzo Commented Mar 3, 2011 at 15:47
4 Answers
Reset to default 3Serialise to JSON using script...
Although this answer uses Ajax, you could instead write the serialised string to an input[type=hidden] in your form
Serializing to JSON in jQuery
You can try this:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert($(this).serialize());
alert(toJSON($(this).serializeArray()));
//return false;
});
function toJSON(obj)
{
var json = '({';
$.each(obj, function(k,v){
var q = typeof v == 'string' ? ~v.indexOf("'") ? '"' : "'" : '';
if (typeof v == 'object')
v = toJSON(v).slice(0,-1).substr(1);
json+= k + ':'+ q + v + q + ',';
});
return json.slice(0,-1)+'})';
};
My fiddle: http://jsfiddle/Achilleterzo/6Zj6n/
If you are using jquery you can look into these two functions .serialize() and .serializeArray()
These functions will help you get the form data, without you having to manually iterate.
Use the jquery form plugin to submit the form via AJAX.
For duplicate field names the default way is usually appending []
to the name - most server-side languages then create an array containing all submitted values. Depending on the language it might also happen without the []
but I'm sure MSDN will help you since you are using ASP.NET for your backend.