11

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:

  1. Serialize the form inputs to JSON
  2. Send the JSON to the server

My questions:

  1. What is the best way to serialize the form inputs to JSON? Perhaps a Backbone only solution?
  2. 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.

A.M.K
  • 16,727
  • 4
  • 32
  • 64
John
  • 3,529
  • 14
  • 42
  • 48

4 Answers4

5

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

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

MCB
  • 2,021
  • 1
  • 18
  • 32
  • exactly what I was looking for -- listens to Rails conventions for form naming, easy to integrate into any backend solution. – Duke Dec 21 '13 at 03:56
3

What is the best way to serialize the form inputs to JSON? Perhaps a Backbone only solution?

Use Backbone.Forms to read the form data into a Model.

For example:

var User = Backbone.Model.extend({
    schema: {
        title:      { type: 'Select', options: ['Mr', 'Mrs', 'Ms'] },
        name:       'Text',
        email:      { validators: ['required', 'email'] },
        birthday:   'Date',
        password:   'Password',
        address:    { type: 'NestedModel', model: Address },
        notes:      { type: 'List', listType: 'Text' }
    }
});

var user = new User();

var form = new Backbone.Form({
    model: user
}).render();

$('body').append(form.el);

Once the form inputs serialized to JavaScript Objects - what is the best way to send JSON to the server?

After that you can sync your model with your REST service. You have to set an url property on your model, and call the save method.

inf3rno
  • 24,976
  • 11
  • 115
  • 197
2

Backbone doesn't make any assumptions of how you implement behavior. It only provides a clean architectural pattern. So the way you have implemented form serialization seems to be fine (similar to or adapted from: Convert form data to JavaScript object with jQuery)

As far as persistence is concerned, you can set the model's attributes when the submit button is clicked.

In your view:

getStatus: function(event){
            var data = JSON.stringify($('form').serializeObject());
            this.model.set(data);

 }

and in your model:

initialize: function(){
   //This will save attributes every time a change event is triggered.
   this.bind("change", this.save);
}
Community
  • 1
  • 1
Aditya Manohar
  • 2,204
  • 1
  • 17
  • 20
  • Instead of binding to "change" event on the model, you could just use `this.model.save(data);` instead of `this.model.set(data);`. – Paul Hoenecke Jan 28 '13 at 03:35
2

Another solution would to be to use the backbone.syphon extension, it allows you to simply submit your form in the same way as an entity would create it:

Backbone.View.extend({
  events: {
    "submit form": "formSubmitted"
  },

  formSubmitted: function(e){
    e.preventDefault();

    var data = Backbone.Syphon.serialize(this);
    this.model.set(data);

    this.model.save();
  }
});
Prisoner
  • 27,391
  • 11
  • 73
  • 102