John Kiernander John Kiernander - 3 months ago 13x
Ajax Question

Wiring an AJAX call in Knockout.js

Apologies if this has been asked before, I have searched but I'm finding it very hard to express my problem in a search friendly way. And I can't figure it out from the knockout documentation, however it seems like a basic question.

I have 3 select lists and a Knockout view model. Selecting a value in the first list updates an observable in the view model. I then need to make an ajax post, sending that value to the server and retrieving a list of values which I put in an observable array in the view model, which will in turn update the other 2 lists.

I'm happy with wiring up to observables and that part is working fine, my question is how and where to trigger the ajax call.

If I trigger it on the change event of the first select it seems to cause a race condition which means it sometimes gets called before the view model has updated. I could trigger it without using the observable, but that doesn't seem very knockoutish.

If I use a custom binding for retrieving values it will cause the ajax call to be made twice and I can't put the retrieval in a function because it needs to run asynchronously (and it would be called twice).

I feel like I need something which listens to an observable and triggers an ajax call without any visual element.

Any help would be gratefully received.


Triggering things that should happen in response to view model changes generally works through subscriptions in knockout.

function ViewModel() {
    var self = this;

    self.someValue = ko.observable();
    self.otherValue = ko.observable();

    self.someValue.subscribe(function (newValue) {
        // do something with newValue, like an Ajax request.

        // assuming jQuery
        $.get("your/url", {val: newValue})
        .done(function (data) {
        .fail(function () {
            alert("could not retrieve value from server");