Reputation: 1146
I am trying to send form fields which are bound to particular observable to my server in the form of JSON object but I receive empty JSON string at server side. I do not want to send the entire view model to accomplish this task. this is the javascript i have so far:
$(document).ready(function(){
ko.applyBindings(new AddSubjectKo());
});
function AddSubjectKo()
{
var self=this;
self.name = ko.observable();
self.quiz = ko.observable();
self.ass = ko.observable();
self.oht = ko.observable();
self.sess = ko.observable();
self.ese = ko.observable();
self.SubjectAdded=function()
{
$.ajax({
url: "api/courses",
type: "post",
data: formToJSON(),
contentType: "application/json",
success: function(data){
alert("success");
},
error:function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
function formToJSON() {
alert(self.name());
return JSON.stringify({
"name": self.name,
"quiz": self.quiz,
"ass": self.ass,
"oht": self.oht,
"sess": self.sess,
"ese": self.ese,
});
}
}
//$("#alert").slideDown();
}
Upvotes: 2
Views: 4231
Reputation: 16465
You can use ko.toJSON
function for this:
function AddSubjectKo()
{
var self=this;
self.name = ko.observable();
self.quiz = ko.observable();
self.ass = ko.observable();
self.oht = ko.observable();
self.sess = ko.observable();
self.ese = ko.observable();
self.SubjectAdded=function()
{
$.ajax({
url: "api/courses",
type: "post",
data: ko.toJSON(self),
contentType: "application/json",
success: function(data){
alert("success");
},
error:function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
}
Upvotes: 8
Reputation: 10515
Just use call the observable (add parenthesis) to grab the values in the observables:
$(document).ready(function(){
ko.applyBindings(new AddSubjectKo());
});
function AddSubjectKo()
{
var self=this;
self.name = ko.observable();
self.quiz = ko.observable();
self.ass = ko.observable();
self.oht = ko.observable();
self.sess = ko.observable();
self.ese = ko.observable();
self.SubjectAdded=function()
{
$.ajax({
url: "api/courses",
type: "post",
data: formToJSON(),
contentType: "application/json",
success: function(data){
alert("success");
},
error:function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
function formToJSON() {
alert(self.name());
return JSON.stringify({
"name": self.name(),
"quiz": self.quiz(),
"ass": self.ass(),
"oht": self.oht(),
"sess": self.sess(),
"ese": self.ese(),
});
}
}
//$("#alert").slideDown();
}
Upvotes: 0