Search code examples
ajaxknockout.jsknockout-mapping-plugin

Knockout js Update viewmodel after ajax post


I am using knockout js and the knockout mapping plugin.

My problem is after calling the ajax post my view (ui) is not updating. Only if I reload the page the data will be updated.

<tbody data-bind="foreach: WorkData">
    <td data-bind="text: id"></td>
    <td data-bind="text: user_name"></td>
    <button class="btn btn-xs btn-success" data-bind="click: $parent.postTmpData" role="button">
        <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
    </button>
</tbody>

<script>
    function ViewModel() {
        var self = this;
        var data = <?php echo json_encode($this->data); ?> ;
        self.WorkData = ko.mapping.fromJS(data);

        self.postTmpData = function(entry) {
            $.post("<?php echo Config::get('URL'); ?>/work/confirmWorkPost/", entry, function(returnedData) {
                ko.mapping.fromJS(returnedData, self);
            })
        }
    }
    ko.applyBindings(new ViewModel());
</script>

Solution

  • This was the solution for me:

    ko.mapping.fromJS(JSON.parse(returnedData), self.WorkData);