26

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.

4
  • 3
    Just a tip, if you're using a browser with a debug console, use that to debug instead of alert(): console.log(myData). It's smart enough to print out objects and everything! Commented Oct 19, 2012 at 2:26
  • It seems there is missing typeof when you are cheking if o[this.name] is defined. Commented Jun 30, 2016 at 10:05
  • Have you check this : stackoverflow.com/questions/1184624/… Commented Mar 26, 2018 at 8:01
  • You can use this, JSON.stringify(Object.fromEntries(formData)); Commented Oct 31, 2019 at 19:35

6 Answers 6

25

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;
  });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Good jsfiddle demo ! Worked for me
all fields are fine except images , json object doesn't has images
6

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.

2 Comments

Is there a proper way to do this with es6 these days? or is jQuery plugin still the best option? 🤔
4

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;
});

Comments

2

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)

Comments

1
$.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 {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

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

1 Comment

worked for me var myForm = document.getElementById("form"); var formData = new FormData(myForm), obj = {}; for (var entry of formData.entries()){ obj[entry[0]] = entry[1]; } console.log(obj);
0

Maybe just use the jquery serialize function?

$("#myform").serialize()

You can do other processing later once you have the JSON object.

3 Comments

I think that encodes as a query string rather than JSON, doesn't it?
@dbaseman Use console.log($("#myform").serialize()); to see!
worked for me var myForm = document.getElementById("form"); var formData = new FormData(myForm), obj = {}; for (var entry of formData.entries()){ obj[entry[0]] = entry[1]; } console.log(obj);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.