Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save values to database using knockout.js using json object

I have got a task to do knockout.js. Here i have a model employee with fields name,country and state. While editing this i want to save it.But when i doing this i can't save it. My edit page is

<%= javascript_include_tag "knockout-2.2.0" %>
<script>
$(document).ready(function() {


    // Here's my data model
        var ViewModel = function(){
            this.country = ko.observable();
            this.state = ko.observable();
            this.name = ko.observable();
            this.fullName = ko.computed(function() {
                return this.country() + " " + this.state();
                 }, this);

            this.save = function(){

                var jsonData = ko.toJSON(ViewModel);
                alert("Could now send this to server: " + JSON.stringify(jsonData));

                $.ajax({
                    url: '/employees/<%[email protected]%>',
                    dataType: 'json',
                    type: 'PUT',
                    data: { total_changes: JSON.stringify(jsonData) },

                    success: function(data){
                        alert("Successful");
                    },
                    failure: function(){
                        alert("Unsuccessful");
                    }
                });
            }
};


        ko.applyBindings(new ViewModel());

});
</script>


<%= form_for(@employee) do |f| %>
  <% if @employee.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@employee.errors.count, "error") %> prohibited this employee from being saved:</h2>

      <ul>
      <% @employee.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <input data-bind='value: name, valueUpdate: "afterkeydown"' />
  </div>
 <div class='label'>
        <%= f.label :country %><br />
        <input data-bind='value: country, valueUpdate: "afterkeydown"' />
  </div>
  <div class="field">
    <%= f.label :state %><br />
    <input data-bind='value: state, valueUpdate: "afterkeydown"' />
  </div>

<p>Name:
<span data-bind="text: name"> </span></p>

<p>Country:
<span data-bind="text: country"> </span></p>

<p>State:
<span data-bind="text: state"> </span></p>
 <button data-bind='click: save'>Submit</button>
  </div>
<% end %>

I cannot get the json object.

like image 577
Nithin Viswanathan Avatar asked Aug 14 '26 14:08

Nithin Viswanathan


1 Answers

Try using

var jsonData = ko.toJSON(this); 

instead of

var jsonData = ko.toJSON(ViewModel);
like image 64
Okky Avatar answered Aug 17 '26 03:08

Okky