Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting serialized form's data to json object

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:

Screen capture

I have tried doing this

var formData = JSON.parse($("#floorplan-form").serializeArray());

But I get this error:

Uncaught SyntaxError: Unexpected token o 
like image 608
Null Reference Avatar asked Apr 25 '14 07:04

Null Reference


People also ask

How do I save HTML form data to JSON file?

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.

Can JSON be serialized?

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.

What is the difference between JSON and 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.


2 Answers

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
like image 121
Hitesh Siddhapura Avatar answered Oct 13 '22 20:10

Hitesh Siddhapura


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);
like image 24
BITS_Python Avatar answered Oct 13 '22 20:10

BITS_Python