1

I am creating a mobile app which relies on jSON to submit forms to a database. I have my submit function:

function sendJson(service, method, json) {
    var request = $.ajax ({
        type: 'POST',
        url: '/remoteserver/service/' + service + '/' + method,
        dataType: 'json',
        async: false,
        data: JSON.stringify(json),
        success: function (msg) {
            alert('Success ' + JSON.stringify(msg.location));
        },
        error: function(msg) {
            alert('YOU SUCK' + JSON.stringify(msg));
        }
     });
}

and currently am using something like this to populate the jSON string:

$("element").click(function(){
    var wrapper = {};
    var location = {};
    wrapper.location = location;
    location.name = $('#name').val();
    location.address1 = $('#address1').val();
    location.address2 = $('#address2').val();
    location.city = $('#city').val();
    location.state = $('#state').val();
    location.country = $('#country').val();
    location.zipCode = $('#zipCode').val();
    location.contactName = $('#contactName').val();
    location.contactPhone = $('#contactPhone').val();
    sendJson("locationService", "createLocation", wrapper);    
});

My question is this - I will have somewhere near 100 forms in this app. How do I go about getting each jSON element(? - IE location.name) to map to the form field w/o having to explicitly state location.name = $('#name).val(); or is this how it's done in jSON? I have searched extensively and everything seems not suited to what Im trying to do. thank you.

Dirty Bird Design
  • 5,333
  • 13
  • 64
  • 121

2 Answers2

2

See Convert form data to JavaScript object with jQuery:

$.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;
};

Now you can serialize it like this:

$('#YourFormID').serialzeObject();
Community
  • 1
  • 1
sroes
  • 14,663
  • 1
  • 53
  • 72
1

You can use .serialize()

Encode a set of form elements as a string for submission.

So you can just do :

var data = $('#YourFormID').serialize();
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111