Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7854063
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T19:55:14+00:00 2026-06-02T19:55:14+00:00

I’ve got a Rails 3.2 app which I’ve started to attach a lot of

  • 0

I’ve got a Rails 3.2 app which I’ve started to attach a lot of knockout.js bindings to. I would like to submit the form in JSON format to my Rails server.

I have a transaction form which has an amount

= form_for(@tran, :html => {"data-bind" => "submit: submitTrans"}) do |f|
    .field
        = f.label :date
        = f.date_select :date
    .field
        = f.label :voucher
        = f.number_field :voucher
    .field
        = f.label :amount
        = f.text_field :amount, "data-bind" => "value: amount, valueUpdate: 'afterkeydown', style: { background: amount() == 0 ? 'red' : 'white' }"
    .field
        = f.label :tax
        = f.text_field :tax, "data-bind" => "value: tax"
    .actions
        = f.submit 'Save'

Here is my knockout code:

#= require knockout

TranViewModel = ->
  # Observables
  self.amount = ko.observable("0")

  # Computed values
  self.tax = ko.computed(
    read: -> (self.amount() / 10).toFixed 2
    write: (value) -> value
    owner: this)


tranViewModel = new TranViewModel()

# Submit through AJAX
self.submitTrans = (formElement) ->
  alert ko.toJSON(tranViewModel)

# Apply keybindings on page load
$(document).ready (event) ->
  ko.applyBindings(tranViewModel)

When I’m using ko.toJSON like this I get ‘undefined’ returned in my alert box.

Do I have to create an instance of my model?
How do I get all my form attributes in JSON format and post these to my rails route ‘/transaction’?

The knockout documentation describes a pushJSON feature but the page doesn’t exist anymore:
http://knockoutjs.com/documentation/submit-binding.html

Update #1

I tried manually sending the json and this allowed me to create an object

self.submitTrans = (formElement) ->
  json = JSON.parse('{"tran": {"amount": "9999"}}')
  $.post("/trans", json, (returnedData) ->
    alert returnedData)

Update #2

I tried a number of things to get my form into JSON for submitting using $.post

self.submitTrans = (formElement) ->
  json = ko.toJSON(tranViewModel)
  $.post("/trans", json, (returnedData) ->
    alert returnedData)

This comes back as undefined. What do I pass to the ko.toJSON?

Update #3

I tried the example from the knockout website:

viewModel =
    firstName : ko.observable("Bert"),
    lastName : ko.observable("Smith"),
    pets : ko.observableArray(["Cat", "Dog", "Fish"]),
    type : "Customer"

self.submitTrans = (formElement) ->
  json = ko.toJSON(viewModel)
  $.post("/trans", json, (returnedData) ->
    alert returnedData)

This correctly formats the viewModel as JSON. This is because viewModel is an object not a function. If I however change my TranViewModel from a function to an object this breaks a lot of my bindings. Which is the correct way of setting up my bindings? Should they be in an object or a function?

Update #4

My examples:
jsfiddle.net/p6Vcc/3 – When clicking submit the ko.toJSON does not collect all formElements, should I be adding observable to all my fields?

jsfiddle.net/p6Vcc/4 – Same example as the previous except recoded in coffeescript, now when clicking the submit it only shows the customers last name, and none of the other fields.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T19:55:16+00:00Added an answer on June 2, 2026 at 7:55 pm

    UPDATE 1
    So looking at the coffee script provided above in the jsfiddle, there is an issue with the javascript being generated by the coffeescript:

      viewModel = __bind(function() {
        this.firstName = ko.observable("Bert");
        return this.lastName = ko.observable("Smith");
      }, this);
    

    Coffeescript always returns the last statement, so you have to add a @ at the end to “return this”

    viewModel = =>
      @firstName = ko.observable("Bert")
      @lastName = ko.observable("Smith")
      @ 
    

    resulting javascript

      viewModel = __bind(function() {
        this.firstName = ko.observable("Bert");
        this.lastName = ko.observable("Smith");
        return this;
      }, this);
    

    Original Answer

    I’m not sure where you are having the trouble. I put your code above into a jsfiddle and it works as expected.

    http://jsfiddle.net/JasonMore/p6Vcc/2/

    Can you update the fiddle to reflect the problem you are having?

    Javascript

    var viewModel = function() {
        this.firstName = ko.observable("Bert");
        this.lastName =ko.observable("Smith");
        this.pets = ko.observableArray(["Cat", "Dog", "Fish"]);
        this.type = "Customer";
    };
    
    var myViewModelInstance = new viewModel();
    
    var jsonToPost = ko.toJSON(myViewModelInstance);
    
    //alert(jsonToPost );
    
    console.log(jsonToPost);
    

    ​

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to run a str_replace or preg_replace which looks for certain words
I would like to count the length of a string with PHP. The string
I've got a string that has curly quotes in it. I'd like to replace
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
We're building an app, our first using Rails 3, and we're having to build
I have a text area in my form which accepts all possible characters from
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.