sarpay
4/28/2014 - 12:56 PM

[jscript] [json] [ajax] convert & serialize form data into json for ajax use - advanced

[jscript] [json] [ajax] convert & serialize form data into json for ajax use - advanced

var SITE_ID;
var form_data = {};

$(document).ready(function () {

	SITE_ID = getQueryParamValByName('site');
	form_data.site_id = SITE_ID;

	//*** add name to form_data.names array
    $('#add_name_btn').click(function (e) {
        e.preventDefault();
        if (typeof form_data.names == 'undefined') form_data.names = new Array();
        if ($('#add_name').val()) {
            form_data.names.push($('#add_name').val());
            $('#add_name').val('');
        }
    });

    //*** remove name from form_data.names array when clicked
    $('.list-names').on('click', 'p a', function (e) {
        e.preventDefault();
        var thisName = $(this).text();
        //*** remove name from form_data.names array
        form_data.names.remove_by_value(thisName);
    });

});


$('#submit_form').submit(function () {

	//*** comma delimited strings
    var names = '';

    //*** auto create form data & convert arrays to comma delimited strings
    for (var key in form_data) {
        var obj = form_data[key];
        if (obj instanceof Array) { //*** convert arrays to comma delimited strings
            for (var i = 0; i < obj.length; i++) {
                if (key == 'names') names += obj[i] + ',';
            }
        } else {
            if ($(this).find('input[name="' + key + '"]').length == 0)
                $(this).append('<input type="hidden" name="' + key + '" value="' + obj + '">');
        }
    }

    //*** Add delimited strings (arrays) to form data
    if (names.length > 0) {
        $(this).append('<input type="hidden" name="names" value="' + names + '">');
    }

    //*** convert form data to json string
    var queryString = $(this).serialize();
    var jsonArray = convertQueryStringToJSON(queryString);
    var jsonString = JSON.stringify(jsonArray);

});


Array.prototype.remove_by_value = function() {
    var what, a = arguments, m = a.length, ax;
    while (m && this.length) {
        what = a[--m];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};


function convertQueryStringToJSON(qs) {

    var pairs = qs.split('&');

    var result = {};
    pairs.forEach(function (pair) {
        pair = pair.split('=');
        result[pair[0]] = decodeURIComponent(pair[1] || '');
    });

    return JSON.parse(JSON.stringify(result));
    
}