JSFiddle - React, Tailwind, and code Playground

Serialize Form to JSON

by Jennifer Perrin

HTML

<h2>Form</h2>
<form action="" method="post"> 
    <input type="hidden" name="CharacterSet" value="utf8"/>
    <p><input type="submit" /></p>
</form>
<h2>JSON</h2>
<pre id="result">
</pre>

CSS

form {
    line-height: 2em;
}
p {
    margin: 5px 0;
}
h2 {
    margin: 10px 0;
    font-size: 1.2em;
    font-weight: bold
}
#result {
    margin: 10px;
    background: #eee;
    padding: 10px;
    height: 40px;
    overflow: auto;
}
input[type=text]{ padding:3px 6px; font-size:12px}

JavaScript

// there is no native support to create object from form, need this plugin 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 {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$(function() {
    createForm();

    $('form').submit(function() {
        // JSO.stringify not supported in browsers older than IE8, FF3.?, need json2.js library for older support
        var data=JSON.stringify($('form').serializeObject())
         // now add ajax, see function below   
         //doAjax( data);   uncomment to run
         
     // utility just to display json this demo   
        $('#result').text(data);
        return false;
    });
});


// demo ajax function for REST
function doAjax( data){
    $.ajax({ url:'REST_url',
             data: data,
             type: 'GET',
             contentType:'application/json',
             dataType:'jsonp', //I assume the REST is jsonp? if not use 'json'
             success:function( returnData){
                 // do something with return
             },
             error: function(){
                 alert('error')
             }
            });        
}


// utility function to create form from array

function createForm() {
    var fields = ["ListName", "FromName", "FromEmail", "Description", "FolderId", "BoB"];
    var html = [];
    $.each(fields, function(i, item) {
        html.push('<input name="' + item + '" type="text" value="'+ item+'"  /><br>');
    });

    $('form').prepend(html.join(''))

}