Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert form data to JSON object [duplicate]

I am trying to convert the HTML form data into a JSON object, I have this thread, but I don't know why it is not working for me. I am using the following code.

<form id="myform" action="" method="post">
    <div class="form-field">
        <label for="title">Title</label>
        <input name="title" id="title" type="text" value="" size="40" aria-required="true">
    </div>
    <div class="form-field form-required">
        <label for="your-name">Your Name</label>
        <input name="yourName" id="yourName" type="text" value="" size="40" aria-required="true">
    </div>
    <div class="form-field">
        <label for="contact-no">Contact No:</label>
        <input name="contact" id="contact" type="text" value="" size="40" aria-required="true">
    </div>
    <div class="form-field">
        <label for="description">Description:</label>
        <textarea name="description" id="description" rows="1" cols="40" aria-required="true"></textarea>
    </div>
    <div class="form-field">
        <label for="email">Email:</label>
        <input name="email" id="email" type="text" value="optional" size="40" aria-required="true">
    </div>
    <div class="form-field">
        <label for="city">City:</label>
        <input name="city" id="city" type="text" value="" size="40" aria-required="true">
    </div>
    <div class="form-field">
        <label for="country">Country:</label>
        <input name="country" id="country" type="text" value="" size="40" aria-required="true">
    </div>
    <div class="form-field">
        <label for="pic1">Picture 1:</label>
        <input type="file" name="pic1" id="pic1">
    </div>
    <div class="form-field">
        <label for="pic2">Picture 2:</label>
        <input type="file" name="pic2" id="pic2">
    </div>
    <div class="form-field">
        <label for="pic3">Picture 3:</label>
        <input type="file" name="pic3" id="pic3">
    </div>
    <div class="form-field">
        <label for="pic4">Picture 4:</label>
        <input type="file" name="pic4" id="pic4">
    </div>
    <div class="form-field">
        <label for="pic5">Picture 5:</label>
        <input type="file" name="pic5" id="pic5">
    </div>
    <div class="form-field">
        <label for="demand">Your Demand:</label>
        <input name="demand" id="demand" type="text" value="" size="40" aria-required="true">
    </div>
    <p class="submit">
        <input type="submit" name="postAd" id="postAd" class="button" value="Post Ad For Review">
    </p>
    <div id="results">hello</div>
</form>

 

$(document).ready(function(){
    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] === undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                alert(this.name);
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    $('#myform').submit(function() {
        $('#result').text(JSON.stringify($('#myform').serializeObject()));
        return false;
    });
});

I tried to debug it, and I noticed that when my function is run, it always runs the code within the else statment.

like image 950
Muaz Usmani Avatar asked Oct 19 '12 02:10

Muaz Usmani


People also ask

How can I convert form data to JSON?

How to Convert Form Data to JSON With Object. fromEntries() Note: For both methods, we can use JSON. stringify() to convert the object into a JSON string, which we can then use to send JSON encoded data to APIs.

How do you convert a React form field value to a JSON object?

You could also use forEach on the FormData object directly: var object = {}; formData. forEach(function(value, key){ object[key] = value; }); var json = JSON. stringify(object);

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.

What is toJSON () in JSON?

if you need to read or clone all of a model's data attributes, use its toJSON() method. This method returns a copy of the attributes as an object (not a JSON string despite its name). (When JSON.


4 Answers

I added above form in JSFiddle and it displays JSON data as output.

Working JSFiddle

$(function() {
  $('form').submit(function() {
     $('#result').text(JSON.stringify($('form').serializeObject()));
    return false;
  });
});
like image 183
Dave Avatar answered Oct 23 '22 07:10

Dave


Use this jQuery plugin .serializeJSON() to convert form data to JSON object.

<form id="my-profile">
<!-- simple attribute -->
    <input type="text" name="fullName" value="Mario Izquierdo" />

<!-- nested attributes -->
    <input type="text" name="address[city]" value="San Francisco" />
    <input type="text" name="address[state][name]" value="California" />
    <input type="text" name="address[state][abbr]" value="CA" />
</form>

Javascript:

$('#my-profile').serializeJSON();

// returns =>
{
    fullName: "Mario Izquierdo",

    address: {
    city: "San Francisco",
    state: {
    name: "California",
    abbr: "CA"
    }
}

serializeJSON() function returns a JSON object.

like image 26
simanacci Avatar answered Oct 23 '22 05:10

simanacci


Working Jsbin example http://jsbin.com/oTimiGE/1/edit

try jquery serializeArray() method

http://api.jquery.com/serializeArray/

$('form').submit(function() {
  console.log($(this).serializeArray());
  return false;
});
like image 4
Amith Avatar answered Oct 23 '22 07:10

Amith


For google searchers,

I've created JSON Array with serialized form like this,

   var jsonArray = [];

   var splittedFormData = $("#formToPost").serialize().split('&');

            $.each(splittedFormData, function (key, value) {

                item = {};
                var splittedValue = value.split('=');               
                item["name"] = splittedValue[0];
                item["value"] = splittedValue[1];
                jsonArray.push(item);
            });

   console.log(jsonArray)
like image 2
Shree Krishna Avatar answered Oct 23 '22 07:10

Shree Krishna