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.

Community
  • 1
  • 1
Muaz Usmani
  • 1,298
  • 6
  • 26
  • 48

6 Answers6

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;
  });
});
Dave
  • 4,376
  • 3
  • 24
  • 37
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.

simanacci
  • 2,197
  • 3
  • 26
  • 35
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;
});
Amith
  • 1,424
  • 1
  • 10
  • 22
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)
Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
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;
    });
});
  • 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); – Shahid Hussain Abbasi Mar 26 '19 at 20:11
0

Maybe just use the jquery serialize function?

$("#myform").serialize()

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

cam
  • 778
  • 6
  • 9