I have a cshtml like the following
@using (Html.BeginForm("Save", "Plans", FormMethod.Post, new { @class = "form-horizontal", id = "floorplan-form" }))
{
@Html.TextBoxFor(m => m.FloorPlan.Name, new { placeholder = "Enter text", @class = "form-control" })
@Html.DropDownListFor(m => m.FloorPlan.GroupId, new SelectList(Model.FloorPlanGroups, "Id", "Name"))
}
In my javascript(in a separate javascript file), I'm trying to serialize this form and convert it into a JSON object.
var formData = $("#floorplan-form").serialize();
console.info(formData);
prints out
FloorPlan.Name=Test&FloorPlan.GroupId=15
And
var formData = $("#floorplan-form").serializeArray();
console.info(formData);
gives me:
I have tried doing this
var formData = JSON.parse($("#floorplan-form").serializeArray());
But I get this error:
Uncaught SyntaxError: Unexpected token o
stringify($("#emails_form"). serializeArray()); If you want to store formData in a JSON file, you need to post it to the server (e.g. per AJAX) and save it. But in that case, you can simply post the form und convert it to JSON on the server itself.
JSON is a format that encodes an object to a string. On the transmission of data or storing is a file, data need to be in byte strings, but as complex objects are in JSON format. Serialization converts these objects into byte strings which is JSON serialization.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.
Change your statement
var formData = JSON.parse($("#floorplan-form").serializeArray());
with
var formData = JSON.stringify(jQuery('#frm').serializeArray()); // store json string
or
var formData = JSON.parse(JSON.stringify(jQuery('#frm').serializeArray())) // store json object
Use the code below!!!
var data = $("form").serialize().split("&");
console.log(data);
var obj={};
for(var key in data)
{
console.log(data[key]);
obj[data[key].split("=")[0]] = data[key].split("=")[1];
}
console.log(obj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With