Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize form inputs to JSON using Backbone.js

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.

like image 465
John Avatar asked Jan 28 '13 01:01

John


4 Answers

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

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

like image 150
MCB Avatar answered Nov 18 '22 15:11

MCB


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.

like image 26
inf3rno Avatar answered Nov 18 '22 15:11

inf3rno


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);
}
like image 2
Aditya Manohar Avatar answered Nov 18 '22 16:11

Aditya Manohar


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();
  }
});
like image 2
Prisoner Avatar answered Nov 18 '22 15:11

Prisoner