0

I'm using knockoutjs with a view model method that makes a jQuery post:

class MyViewModel
{
    public id = ko.observable<number>();
    public name = ko.observable<string>();
    ...

    public myMethod = function () 
       { 
           var obj = ANYTHING
           $.post('/api/controller/update', obj)
       }
} 

And I invoke this by binding a click attribute to the view model:

<a href="#" data-bind="click: myMethod">Do Something</a>

If I click the button, it calls the method. If the method posts with no data, it works fine. But if I pass an object of any kind, even an empty one {}, the call fails with:

SecurityError: The operation is insecure.
var propertyValue = mapInputCallback(rootObject[indexer]);
http://localhost:35179/Scripts/knockout-3.2.0.debug.js (line 1904)

I've tried all kinds of objects here, and it seems that any object at all causes this problem, whereas using no data works fine.

So, knockout doesn't like something about this, but I can't figure out what it is, and this is completely blocking my progress. The puzzling thing to me is how I could get an error in knockout code when calling a method in jQuery that has nothing to do with the knockout code (other than that the callback method was called back from knockout).

Joshua Frank
  • 13,120
  • 11
  • 46
  • 95

1 Answers1

1

You need to call JSON.stringify on the object and set the contentType to 'application/json'. In your case this would be:

$.ajax({
    url: '/api/controller/update',
    type: 'POST',
    data: JSON.stringify(obj),
    contentType: 'application/json'
});

Note that the jquery.post method is shorthand for the jquery.ajax method. More info is available here: http://api.jquery.com/jquery.post/

However, the SecurityError: The operation is insecure. that you're getting is one that is usually thrown in relation to cross-origin issues, typically when running a website under the file:/// protocol. Please see here: SecurityError: The operation is insecure - window.history.pushState()

Community
  • 1
  • 1
Matthew James Davis
  • 12,134
  • 7
  • 61
  • 90
  • Thanks, that did the trick. I was wondering about content type and object vs. string format, but that security error confused me into thinking it was a knockout issue. But I'm not doing anything cross site, so I remain puzzled. I wonder if internally the `ajax` method gets confused about the url if the data object isn't a string. – Joshua Frank Nov 12 '14 at 00:50