2

I've been working with the JTemplates plugin which I've used to create a form that is bound to a json object via a template. Works perfectly. What I would like to do though is instead of submitting the form I'd like to re-serialize it back into the json object from which it originated and pass it back to the controller method as a json string. What's the best way to serialize the object back into its original format?

jamesaharvey
  • 14,023
  • 15
  • 52
  • 63
Bob J.
  • 21
  • 1

1 Answers1

1

I use serializeObject and toJson to accomplish this.

var yourForm = $('#formId');
//Serialize form elements and make into json object
var jsonObject = $.toJSON(yourForm.serializeObject());

serializeObject (jquery)

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           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;
};

toJSON

Using the json.js library at: https://github.com/douglascrockford/JSON-js

Sam Saffron
  • 128,308
  • 78
  • 326
  • 506
Amin
  • 11
  • 1