Serialize form inputs to JSON using Backbone.js

backbone.js, javascript, jquery, json, serialization

Solution

For just serializing to JSON there's this option as well

https://github.com/marioizquierdo/jquery.serializeJSON

Problem

I'm working on RESTful application - I'm using Java on the server side and Backbone for the Front End. The 2 will communicate via JSON. My App has quite a few forms and I would like to: - Serialize the form inputs to JSON - Send the JSON to the server My questions: - What is the best way to serialize the form inputs to JSON? Perhaps a Backbone only solution? - Once the form inputs serialized to JavaScript Objects - what is the best way to send JSON to the server? My code so far: Javascript and Backbone ``` $(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; }; //Model var SignupForm = Backbone.Model.extend(); //View var SignupView = Backbone.View.extend({ el: '.signupForm', events: { 'click input.submit': 'getStatus' }, getStatus: function(event){ var data = JSON.stringify($('form').serializeObject()); $('.test').html(data); return false; } }); var signupForm = new SignupForm(); var signupView = new SignupView({ model: signupForm }); }); ``` HTML ``` <div class="signupForm"> <form class"signup"> <label for="name" >Name:</label> <input type="text" id="name" name="name" /> <label for="surname" >Surname:</label> <input type="text" id="surname" name="surname" /> <input type="submit" value="submit" class="submit" /> </form> <div class="test"></div> </div> ``` I'm new to Backbone so sorry if this is trivial. I'm keen to code my application the best way as possible so please feel free to tell me if there is a better way to do this. Thanks a lot.

Original source

Related problems